How to redirect users to a random post

Create a new file and name it page-random.php. Paste the code below in it:

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

Once done, upload the page-random.php file to your theme directory. Then, login to your WordPress dashboard and create a new page, called “random” (You have to call it random, otherwise, the standard page layout will apply, see WP Codex for more details about page hierarchy).

After you published the random page, any user who’ll visit the http://www.yourwebsite.com/random page will be automatically redirected to a random post.

By the way, I just created a Facebook page for my websites (This include WPRecipes as well as CatsWhoCode) so don’t hesitate to “like” it!

Thanks to Smashing Magazine for the cool tip!

Leave a Reply

Your email address will not be published. Required fields are marked *