Random post order with correct pagination

Random post order with correct pagination
5 (100%) 1 vote

You can find many resources on the internet to randomize the wordpress posts, simply add ‘orderby’ => ‘rand’ in wp query :

query_posts("orderby=rand");

The issue with this method is that it breaks wordpress pagination. If you navigate to the second page of the results, the random posts which are returned may contain posts that you have already viewed.

Here is an easy way to randomize the posts order with correct pagination

Simply add the next piece of code to Your wordpress theme, at the beginning of functions.php file:

<?php
session_start();
add_filter( 'posts_orderby', 'randomise_with_pagination' );
function randomise_with_pagination( $orderby ) {
	if( is_front_page() ) {
	  	// Reset seed on load of initial archive page
		if( ! get_query_var( 'paged' ) || get_query_var( 'paged' ) == 0 || get_query_var( 'paged' ) == 1 ) {
			if( isset( $_SESSION['seed'] ) ) {
				unset( $_SESSION['seed'] );
			}
		}
	
		// Get seed from session variable if it exists
		$seed = false;
		if( isset( $_SESSION['seed'] ) ) {
			$seed = $_SESSION['seed'];
		}
	
	    	// Set new seed if none exists
	    	if ( ! $seed ) {
	      		$seed = rand();
	      		$_SESSION['seed'] = $seed;
	    	}
	
	    	// Update ORDER BY clause to use seed
	    	$orderby = 'RAND(' . $seed . ')';
	}
	return $orderby;
}
?>
Note

This code randomize the order to the front page only (because it has is_front_page() condition), but you can change the conditional to target whatever page or post type archive that you wish.

Leave a Reply

Your email address will not be published. Required fields are marked *