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