WordPress Snippets at WPcustoms

Randomize your posts

Add this code snippet to your functions.php file. It jumps into the pre_get_posts hook and add the argument “orderby=rand” to the main queries. This way your posts get randomized in its order. Feel free to adjust the conditional tags. You can also use this for custom post types.


/**
 * Snippet Name: Randomize your posts
 * Snippet URL: https://wpcustoms.net/snippets/randomize-your-posts/
 */
  add_action( 'pre_get_posts', 'random_posts' );
function random_posts( $query ) {
  if ( $query->is_home() && !$query->is_paged() && $query->is_main_query() ) {
    $query->set( 'orderby', 'rand' );
  }
}