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.







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.
You can’t with this method. You would have to use WP_Query and custom page templates to accomplish what you want.
Perfect! It works for my Thesis site.
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
Not using W3tc plugin and read the thing you told about WP SEO plugin. Still it doesn’t work for me.
Why ?
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.
Any other method of redirection? You suggest?
Well, now it is working I am using http://domain.com/index.php?random=1
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?
The get_posts has a lot of parameters. It accepts all parameters from the WP_Query. You can use the time parameter to achieve that.
http://codex.wordpress.org/Class_Reference/WP_Query#Time_Parameters
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…
Probably because something on your server is not configured right.
I added <code>RewriteRule ^random/ /index.php?random=1</code> between the WordPress rewrite tags (# BEGIN WordPress.) This gets around the 404 error.
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?
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!!
@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.
@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.
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!!
MY problems were same as Joshua Dorkin but thank god i have got it woring now!
Very useful, will try it out in future !
How would one do this for #bbPress?
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?
@jrdorkin Open a blank plugin file and paste it in there. Do it as a plugin. See if that works.
@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?
@jrdorkin You need to name the plugin as well.http://ottopress.com/2011/creating-a-site-specific-snippets-plugin/
@wpbeginner Ahh . . . nice. Still getting a 404
@jrdorkin try doing: yourdomain.com/?random=1
@wpbeginner Yep – that did it. You guys rock!