Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to Redirect Users to a Random Post in WordPress

Last updated on by
Follow WPBeginner on YouTube
How to Redirect Users to a Random Post in WordPress

One of the new features that we added in our new design is this feature called “Explore” that you see prominent throughout our entire network. When a user clicks on this button, they are taken to a random post on a site. Previously, we did it so users were taken to a page which would display a random post. There were quite some issues with that. The major one being the user never knew the actual URL of the page. When launching our newest site List25, we thought it would be cool to add a button called I’m feeling curious and let users browse that way. At this time, I was speaking at WordCamp Louisville. A friend of ours whom I look up to for a lot of things (@Otto42) happened to be in attendance. During my session, Otto wrote this snippet rather than listening to my talk (like he really needed to learn it). Well long story short, in this article, we will show you how to redirect users to a random post in WordPress.

Open your theme’s functions.php file or create a blank plugin file and paste the following code:

add_action('init','random_add_rewrite');
function random_add_rewrite() {
       global $wp;
       $wp->add_query_var('random');
       add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}

add_action('template_redirect','random_template');
function random_template() {
       if (get_query_var('random') == 1) {
               $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
               foreach($posts as $post) {
                       $link = get_permalink($post);
               }
               wp_redirect($link,307);
               exit;
       }
}

That’s it and you are done. Now create a button that links to yourdomain.com/random/ and the snippet above will take care of the rest.

Explanation of the snippet:

This snippet first adds a query variable Random. Then it uses template_redirect hook in WordPress and say if the the variable random is there, then get a post from the post type “Post” randomly. Then it does a simple 307 redirect.

The reason why the snippet uses 307 redirect is because it is a temporary redirection. Browsers often cache 302 redirect which is famously known for temporary redirects.

Few bugs we ran into:

If you are using W3 Total Cache and you have database caching on, then you need to add the following rules in the exclusion list.

/random/
/index.php?random=1

If you are using Yoast’s WordPress SEO plugin, then don’t use Redirect Ugly URLs checkbox in the permalinks area otherwise this code will not work.

Now you can create a little Explore button like we have on our site.


Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
  • Domingos

    How can I have the link to be like: yourdomain/random-post
    just like at list25?

    • http://www.wpbeginner.com/ WPBeginner Support

      Try changing line 5 in the code snippet given in the article like this:

       add_rewrite_rule('random-post/?$', 'index.php?random=1', 'top');
      
      • Domingos

        I’ve done what you said, but then I get an 404 error. It’s only working when I keep it at:
        add_rewrite_rule(‘random/?$’, ‘index.php?random=1′, ‘top’);

        It’s not theme related because it’s also not working on the default wordpress themes.

    • http://nodws.com/ Nodws

      create a page named Random
      in your template create a file named page-random.php and add line 11 to 15, done

  • Satyapriya

    Awesome! Thank you so much for this <3

    To get it work for my 7 custom post types I had to add the following code to my get_posts query:

    get_posts('post_type[]=news&post_type[]=questions&post_type[]=videos&post_type[]=documentaries&post_type[]=ted-talks&post_type[]=memes&post_type[]=music&orderby=rand&numberposts=1');

    I'm curious, is it possible to create 7 different buttons, one for each custom post type, displaying a random post for only that post type? If so, how would I do this?

  • Balazs Hende

    Hi,
    is it necessary to use rel=”nofollow” after the href=”domain.com/index.php?random=1″ ?
    Btw it’s great!
    Thanks in advance

    • http://www.wpbeginner.com/ WPBeginner Support

      No it is not but recommended.

  • Franco

    Hi
    Thanks for the nice function. works great.

    When Otto maybe got a minute. is it possible to hack the function to work only for specific categories ?

    Thanks

  • John

    Hi There,

    Do you have any way to work around this below problem yet?

    >>”Installed the code and it works fine in Opera and Chrome but Internet Explorer and fox just keep showing the same article over and over again. Any suggestions?”

    Thanks

  • Chris Hughes

    Installed the code and it works fine in Opera and Chrome but Internet Explorer and fox just keep showing the same article over and over again. Any suggestions?

    • http://www.wpbeginner.com Editorial Staff

      It seems that IE is caching the URLs. Will have to look into the support for that.

  • Jacob

    Hey thanks for this man. How can I edit it so that a certain page generates random posts only from a certain category of posts? So posts with category A generate randomly on page A with an iframe and the same for category B and page B.

    I appreciate this.

    • http://www.wpbeginner.com Editorial Staff

      You can’t with this method. You would have to use WP_Query and custom page templates to accomplish what you want.

  • Usman

    Perfect! It works for my Thesis site.

  • JasonG

    Hi,

    Just wanted to say thanks for this. I was getting a 404 at first, but using /?random=1 worked a treat!

    Thanks again

    Jason

  • Ahmad Awais

    Not using W3tc plugin and read the thing you told about WP SEO plugin. Still it doesn’t work for me.
    Why ?

    • http://www.wpbeginner.com Editorial Staff

      Not sure. Can’t see the code that you have on your site. But it’s probably because of a bad plugin or some bad function. This code is written by Otto who is one of the core contributor of WordPress. It works flawlessly on our site and many others.

  • Matt

    Hi there, love this and it worked perfectly for me! Would it be possible to limit the random post pool to only using posts from a certain timeframe? ex. the last few months?

  • http://TheFallJourney.com/ Rene

    Using “mydomain.com/random/” gives me a 404 page but using “mydomain.com//index.php?random=1″ gives me a random post. Why doesn’t “random” work and the other one does?

    Thanks…

    • wpbeginner

      Probably because something on your server is not configured right.

    • http://martinwebster.eu/ Martin Webster

      I added <code>RewriteRule ^random/ /index.php?random=1</code> between the WordPress rewrite tags (# BEGIN WordPress.) This gets around the 404 error.

  • Vishal Gupta

    Very nice trick. Thanks for sharing it. I successfully implemented it using domainname.com/?random=1

    domainname.com/ramdom didnt work like others. It showed 404 not found error. You should add this to article so that people can try both of the URLs.

    PS: One thing to ask! Will this method slow down the server or will it cause any extra load on server as we are going to have lots of redirect?

  • ErikAhrend

    Hi. I have been trying this trick but doesn´t seem to be working. Mind me, my coding skills are near to ZERO.

    – I have created a “random-post” directory in plugins folder.

    – I have created a “random.php” file inside this folder. In this blank document I pasted the following code:

    Plugin Name: Random Post

    Description: Creates a random post to diaplay from action call button..

    */

    add_action(‘init’,’random_add_rewrite’);

    function random_add_rewrite() {

    global $wp;

    $wp->add_query_var(‘random’);

    add_rewrite_rule(‘random/?$’, ‘appcaffe.com/?random=1′, ‘top’);

    }

    add_action(‘template_redirect’,’random_template’);

    function random_template() {

    if (get_query_var(‘random’) == 1) {

    $posts = get_posts(‘post_type=post&orderby=rand&numberposts=1′);

    foreach($posts as $post) {

    $link = get_permalink($post);

    } wp_redirect($link,307);

    exit;

    }

    }

    I have activated the plugin and created a button that links to: http://appcaffe.com/random/

    As a result I am getting a 404 page.. Any tips?

    Thanks!!

    • ErikAhrend

      @ayushwhizkid@ErikAhrend Hi and thanks for your reply. I tried the plugin you suggested and it gave me a number of problems (plus it didn´t work). I did, however try the random-redirect plugin (http://wordpress.org/extend/plugins/random-redirect/) and it worked like a charm..

      Thanks again for the help.

    • ErikAhrend

      @ayushwhizkid@ErikAhrend Hi and thanks for your reply. I tried the plugin you suggested and it gave me a number of problems (plus it didn´t work). I did, however try the random-redirect plugin (http://wordpress.org/extend/plugins/random-redirect/) and it worked like a charm..

      Thanks again for the help.

  • ErikAhrend

    Hi. I have been trying this trick but doesn´t seem to be working. Mind me, my coding skills are near to ZERO.

    – I have created a “random-post” directory in plugins folder.

    – I have created a “random.php” file inside this folder. In this blank document I pasted the following code:

    <?php /*

    Plugin Name: Random Post

    Description: Creates a random post to diaplay from action call button..

    */

    add_action(‘init’,’random_add_rewrite’);

    function random_add_rewrite() {

    global $wp;

    $wp->add_query_var(‘random’);

    add_rewrite_rule(‘random/?$’, ‘index.php?random=1′, ‘top’);

    }

    add_action(‘template_redirect’,’random_template’);

    function random_template() {

    if (get_query_var(‘random’) == 1) {

    $posts = get_posts(‘post_type=post&orderby=rand&numberposts=1′);

    foreach($posts as $post) {

    $link = get_permalink($post);

    } wp_redirect($link,307);

    exit;

    }

    }

    As a result I am getting a 404 page.. Any tips?

    Thanks!!

  • ayushwhizkid

    MY problems were same as Joshua Dorkin but thank god i have got it woring now!

  • http://bestbloggingtools.com/ faizanutd

    Very useful, will try it out in future !

  • MichealKennedy

    How would one do this for #bbPress?

  • http://www.biggerpockets.com/ jrdorkin

    How would I add this on a blog using Thesis? I tried adding it to custom_functions.php and it didn’t work. Any ideas for a work-around using that theme?

    • wpbeginner

      @jrdorkin Open a blank plugin file and paste it in there. Do it as a plugin. See if that works.

      • http://www.biggerpockets.com/ jrdorkin

        @wpbeginner Just plugin the info into a blank doc and save it as random.php or something of that sort? I tried that and uploaded it to the plugins folder, but it didn’t show as a plugin I can authorize (I’m admittedly not a great coder – clearly). Is there something else I need to save to the file for WP to register it as a plugin?

        • wpbeginner

          @jrdorkin You need to name the plugin as well.http://ottopress.com/2011/creating-a-site-specific-snippets-plugin/

        • http://www.biggerpockets.com/ jrdorkin

          @wpbeginner Ahh . . . nice. Still getting a 404

        • wpbeginner

          @jrdorkin try doing: yourdomain.com/?random=1

        • http://www.biggerpockets.com/ jrdorkin

          @wpbeginner Yep – that did it. You guys rock!