Create a Random Redirect in WordPress
If you’ve ever been to a website that had a cool random page option like Wikipedia, and wanted to do something similar on your own WordPress site, here’s a great little tutorial for you.
Creating a Random Page
Step one to creating a random page in WordPress is to create a new page under Pages > Add New. When you create the page, you can set the title to Random or Random Article but make sure the Permalink also uses the word random as demonstrated in this image.
If you need to, you can click Edit to change the permalink to read correctly. Once you’re done, click Publish and you’ve created a new page.
Creating a Random Page Template
Now that you have a page, you need to assign unique logic to the page. This is accomplished by adding a new page template to your WordPress theme. Let’s start by locating the page.php and duplicating it. Save the new file as page-random.php in the same directory and upload it to your website.
When the Random page is loaded, you’ll see the contents on page-ramdom.php instead of page.php. Remember, if you’ve selected a different permalink you can change the filename to reflect this.
Adding Logic to the Random Page Template
Now that we’ve created the random page, you’ll want to add new code to the page which creates the redirect effect.
Let’s start by opening page-random.php and deleting all the content. The old content was copied from page.php and we won’t be needing it for this new page.
Next, paste the following code into your template:
<?php
// random page code
$args=array(
'numberposts'=> 1,
'orderby'=> 'rand',
);
$feature_post = get_posts($args);
foreach( $feature_post as $post ) : setup_postdata( $post );
header('location: '.get_permalink());
endforeach;
?>
What it does is simply load a single, random post from your WordPress archives and redirect the user to the article.


3 Comments
Cláudio Novais
Thank you very much! I’m using it right now!
24 Jan 2011 06:01 pm
Christopher Ross
Otto posted a fantastic alternative to this code on http://ottopress.com/2011/random-post-snippet/ that’s really very clever.
08 Nov 2011 09:11 pm
Carlos
Works perfect!!!!
Thank you!
24 Nov 2011 04:11 pm
Leave a Comment