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.

1x1.trans Create a Random Redirect in WordPress

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 thoughts on “Create a Random Redirect in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>