Random post order with correct pagination

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


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:

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;

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.

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Reply

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