Skip to content

Instantly share code, notes, and snippets.

@hlashbrooke
Last active July 4, 2022 21:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save hlashbrooke/6298714 to your computer and use it in GitHub Desktop.
Save hlashbrooke/6298714 to your computer and use it in GitHub Desktop.
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;
}
?>
Copy link

ghost commented Nov 26, 2017

Thank you @hlashbrooke. The code is absolutely great.
How can it be applied to archive pages? (random posts and pagination for category and tag archive pages)

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