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 experts 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 »

Comments

  1. Gabrielle says:

    Hi, i created ul li list that will show 6 random posts,
    how can i add button to this list that will refresh only my
    list of random post, not entire page?

  2. Richie says:

    This code needs to be changed.. add flush_rewrite_rules(); after the “add_rewrite_rule” line. There is a core wordpress problem which requires that line for the rewriting to work properly.

  3. Graeme Voigt says:

    GREAT! Thanks for this. I got a 404 at first but then used /?random=1 and it worked fine!
    THANK YOU!

  4. XP Mai says:

    Could it be plugin(s) conflict?

  5. Karen says:

    I have been trying to use this with the Crawford theme. When I tried to copy and past the code into functions.php, I got the white screen of death. I went the blank plugin route instead, and when I tried to activate the plugin I again got the white screen of death. What’s goin on??

  6. kenny says:

    thank you, works great

  7. burhan says:

    wp surer cache source of the problem firefox

    chrome test no problem

  8. burhan says:

    hi,

    my using
    /index.php?random=1

    wp super cache problem always the same post

  9. Domingos says:

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

    • WPBeginner Support says:

      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 says:

        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.

    • Nodws says:

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

  10. Satyapriya says:

    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?

  11. Balazs Hende says:

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

  12. Franco says:

    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

  13. John says:

    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

  14. Chris Hughes says:

    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?

  15. Jacob says:

    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.

    • Editorial Staff says:

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

  16. Usman says:

    Perfect! It works for my Thesis site.

  17. JasonG says:

    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

  18. Ahmad Awais says:

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

  19. Matt says:

    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?

  20. Rene says:

    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 says:

      Probably because something on your server is not configured right.

    • Martin Webster says:

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

  21. Vishal Gupta says:

    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?

  22. ErikAhrend says:

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

  23. ErikAhrend says:

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

  24. ayushwhizkid says:

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

  25. faizanutd says:

    Very useful, will try it out in future !

  26. MichealKennedy says:

    How would one do this for #bbPress?

  27. jrdorkin says:

    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?

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.