making a random page on your wordpress website

here’s my own solution to this:

step one: make a file in your template directory and add this as the content:

<?php
/*
Template Name: Random Post Redirector
Use on page to send viewer to random post optionally mod query
*/

// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'rand',
'post__not_in' => get_option("sticky_posts"),
);

// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );

while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();

// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>

Step two: Create a page and select the custom template you created above.

Optional Step three: If you want your front page to always show a random post, Go to your “reading” settings page at www.example.com/wp-admin/options-reading.php and select the “static page” option to use the page you created above. Word of caution though, having this on your front page may cause some pretty big server spikes if you don’t have caching turned up to 11.

Leave a Reply