Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
WordPress: Display posts in a random order, but retain persistent pagination
<?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;
}
?>

Thank you for this great snippet. I've been using it for a few months.

But now it stopped working, I don't know why. The posts are still displayed in a random order, but the pagination doesn't work anymore -- pages 2, 3 etc. will often show repeated posts.

I'd be glad if you could update the snippet (if it's possible to correct this behaviour with an update, that is).

[UPDATE] Actually, it seems the issue is with caching. I tested the snippet with W3 Total Cache disabled, and it worked perfectly. Once I enabled W3 Total Cache, the pagination stopped working properly.

[UPDATE 2] I did some additional tests. Yes, it's a caching issue. But the problem is Varnish, not W3 Total Cache. My bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment