DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

What about giving a new life to your old posts by creating a page template that will redirect readers to a random post? Today, I’m going to show you how to easily create this kind of page.

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 ) );

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!


  1. You should make the redirect using a 307 HTTP code, that way search bots know that it’s a temporary redirect, like so:

    wp_redirect ( get_permalink ( $post->ID ), 307 );

  2. With wp_redirect() I usually use status code 307 to indicate that this is a temporary redirect.

  3. Thanks for the simple and handy code.

  4. query_posts(‘posts_per_page=1&orderby=rand’); would not be any easier?

  5. Trying again, this time with character codes…

    Add “<? PHP” to the top or page-random.php, and “?>” to the bottom. If this doesn’t work, I’m trying to say to add the PHP tag to the top ad close the tag at the bottom… *sigh*

  6. Awesome – I never thought of doing this random redirect, but it is so simple it may be something fun to add! Thanks! 🙂

  7. Hi, what if I need it to redirect randomly from a pool of few pages, say 5 pages? Eg: pages ID is 1,2,3,4,5

    So do I just put the numbers as in:
    wp_redirect ( get_permalink ( $post->1,2,3,4,5 ) );

    Sorry, I am not good at coding.. 🙁

Leave a Comment

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