X

Display posts in a random order, but 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.


Code Snippet:

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;
}

Comments  Leave a Reply

  1. 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.

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

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!