Home / functions.php / Display posts in a random order, but retain persistent pagination
  • How to Display posts in a random order, but retain persistent pagination

    display-posts-random-order-retain-persistent-pagination

    Randomising the order of the returned posts in a WordPress query is easy – simply add 'orderby' => 'rand' to the arguments and you’re good to go – this is great, until you need to paginate the results. As soon as you navigate to the second page of the results, the posts are returned randomly once again and you get an entirely different set of posts that may or may not contain posts that you have already viewed – if you’ve experienced this before then you’ll know exactly how frustrating it can be. The first thing we need to do is make sure our PHP session is initiated and then we can use the 'posts_orderby' filter to handle the persistent randomisation.

    ( click code to copy )

    wordpress snippet : 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;
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    posts_orderby, query, init, add_filter, is_front_page, get_query_var,
  • Ralph Warom

    Thanks a lot. I had been looking for code like this to share more articles with the rrader at the end of my site.

  • Paul

    Is this supposed to fix the ‘second page random posts’ issue? Or is it to illustrate the issue? I’ve used it to generate some randomly ordered posts, but when I go to the second page, the randomisation obviously starts again, because I may or may not get the same posts appearing.