Random post selection
-
Most online search responses to this requirement show how to randomize the selection ordering only, not the selection itself. I wanted a solution not tied to using a widget or shortcode, but which I could use in any context. Solution below for your child theme’s functions.php. You can see it (at the time of writing) working on my homepage at lodestarbooks.com, where typing 10403 as the number of posts in my Divi blog grid gives me 4 posts at random, with an offset of 3. This might get slow with a very large number of matching posts, but I doubt my site will hit that problem. A better high-volume solution would involve selecting only the required number of posts randomly at the outset — non-trivial, but I might get there if you don’t first.
/* Select random posts by selecting all matching ones, applying the offset if any, shuffling the remainder, then slicing off the required number; randomness is requested by the posts_per_page being 5 digits long, where digits 2 and 3 are the number of posts required and the rightmost two digits are the offset; eg 10403 gets 4 posts randomly, with an offset of 3. This *may* get slow where the number of matching posts is very large */ add_action( 'pre_get_posts', function( $query ) { $actionCode = (int) $query->get('posts_per_page'); if ( $actionCode > 1000 ) { $query->set('_randomize', $actionCode % 1000); $query->set('posts_per_page', -1); } }, 10, 1 ); add_filter( 'the_posts', function( $posts, $query ) { if( $actionCode = (int) $query->get( '_randomize' ) ) { $no_posts = (int) ($actionCode / 100); $offset = $actionCode % 100; $posts = array_slice( $posts, $offset ); shuffle( $posts ); $posts = array_slice( $posts, 0, $no_posts ); } return $posts; }, 10, 2 );
- The topic ‘Random post selection’ is closed to new replies.