Post Pic

How to redirect users to a random post

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

7 Responses

May 01 2012 20:09

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

May 01 2012 21:12

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

May 01 2012 21:35

Thanks for the simple and handy code.

May 02 2012 05:07

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

Jun 29 2012 23:54

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*

Sep 25 2012 06:32

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

Oct 06 2012 17:37

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.. :(

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox