About The Author

Goce Mitevski is an independent designer and the founder of Nicer2. He’s passionate about WordPress, Photography, 3D Visualization, Drawing, Illustration … More about Goce

Random Redirection In WordPress

Quick Summary

If you run an online magazine, most of your readers will never go through your archive, even if you design a neat archive page. It’s not you; it’s just that going through archives is not very popular these days. So, how do you actually make readers dig in without forcing them? How do you invite them to (re)read in a way that’s not boring? How do you make your WordPress magazine more interactive? random-redirection-wordpress-wikipedia-wikihow Call it recycling if you like, but random redirection doesn’t have to be about retreading familiar territory. Through random redirection, you offer readers a chance to hop randomly through your posts and discover content that they somehow missed. The concept really is simple. All you have to do is create a hyperlink — named, say, “Random article” — that when clicked will redirect the reader to a randomly pulled article.

Table of Contents
Membership counter

Members support Smashing

Wonderful, friendly people who keep this lil' site alive — and get smarter every day.

Are you smashing, too? →

If you run an online magazine, most of your readers will never go through your archive, even if you design a neat archive page. It’s not you; it’s just that going through archives is not very popular these days. So, how do you actually make readers dig in without forcing them? How do you invite them to (re)read in a way that’s not boring? How do you make your WordPress magazine more interactive?

Have you tried random redirection?

Call it recycling if you like, but random redirection doesn’t have to be about retreading familiar territory. Through random redirection, you offer readers a chance to hop randomly through your posts and discover content that they somehow missed.

Further Reading on SmashingMag:

The concept really is simple. All you have to do is create a hyperlink — named, say, “Random article” — that when clicked will redirect the reader to a randomly pulled article.

WordPress supports random redirection out of the box, but it’s not very obvious. All of the required functions are in the core, but they’re not bound in any common workflow. For instance, generating a “Random article” link in the main menu simply by checking a box in the administration section is not possible.

To implement random redirection in WordPress, you will usually need to work with the following three things:

  • A page to process the redirection,
  • A query to pick a post from the database,
  • Some sort of mechanism to initiate the redirection.

Of course, many of you might want to use a plugin. That’s absolutely fine, as long as you don’t need any more features than what it offers.

You would probably come across Matt Mullenweg’s Random Redirect plugin first. Then you would probably try Random Redirect 2, which expands on that.

Instead, today I’ll guide you through a custom implementation that I use. It’s not the “right” way to implement random redirection; it’s just one plugin-less solution to start with and build on.

We’ll be working with the three things mentioned in the list further up. Let’s go into the concept in detail.

The Simple Solution

We’ll be implementing random redirection through a WordPress page, which we’ll simply call “Random.” Creating this new page in the admin section will be the last step we take, though. Why? Because we don’t want to make the redirection page accessible before it’s been fully implemented.

According to the WordPress template hierarchy, if you create a page template file named page-random.php, whenever a user loads the page assigned to the slug random, it will load through the page-random.php template. This is a well-known benefit of WordPress and is also useful for our random redirection.

The page-random.php page template will not include the usual calls for loading the header, sidebar and footer templates, because our “Random” page won’t generate any visible output for the user; it will simply jump (that is, redirect) to a randomly chosen article. Because we need to make only one request from the database (to select one random article to redirect to), we will make only one call to the get_posts() function in the template, and we’ll use a foreach loop to process the output.

The get_posts() function receives only two arguments as its input, with which we’re specifying that we want to fetch only one post randomly. The orderby argument set to rand is what enables randomization in WordPress. We don’t need to specify the post_type because it’s already set to post by default for get_posts(). We also don’t need to specify the post_status because it defaults to publish, which is exactly what we need.

// source code from page-random.php


  



// Random Redirection Page Template

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

So, we first save the data from get_posts() into a variable and then process it through the foreach loop. The magic happens in the foreach loop, when the redirection is initiated through the wp_redirect() function, which has the post’s permalink as its input.

random-redirection-wordpress-add-random-page
Creating a “Random” page through WordPress’ administration interface

Now the only thing we need to do is go to WordPress’s administration section, create a blank new page with the slug random, and publish it. Then, when you visit http://www.mywebsite.com/random/, you will be automatically redirected to a random article.

random-redirection-wordpress-add-random-page-main-menu
Adding a link to the “Random” page in the main menu.

We can now add a link in the main menu to make the page easily accessible.

Using WP_Query Instead

The implementation above can easily be adapted to directly use the WP_Query class, instead of the get_posts() function.

// source code from page-random.php implemented through WP_Query

// Random Redirection Page Template

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

The main benefit of using WP_Query is that it can accept more arguments than the get_posts() function, thus offering more flexibility when you’re building specific queries.

A Few More Examples

With both get_posts() and WP_Query, we can be very specific and implement random redirection for posts of custom types or posts that belong to particular categories.

For example, we could make WordPress redirect to articles published only in the “Travel” category:

// set arguments for WP_Query()
$args = array(
    'category_name' => 'travel', // remember, we are using category slug here
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Or we could redirect to posts from all categories except “Uncategorized”:

// set arguments for WP_Query()
$args = array(
    'category__not_in' => array(1), // id of the category to be excluded
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

How about limiting randomization to posts published in 2011?

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'year' => '2011',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Maybe even add filtering by custom field? Let’s limit random redirection to posts that have a custom field with the value strawberry assigned.

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'meta_value' => 'strawberry',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

The example above could easily be transformed to limit random redirection to posts that have the custom field long_description assigned. Remember, our only condition here is for the post to have the custom field assigned. It doesn’t matter what the value of the long_description custom field is.

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'meta_key' => 'long_description',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Instead of posts, we could also implement random redirection for pages:

// set arguments for WP_Query()
$args = array(
    'post_type' => 'page',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

We could even create random redirection for custom post types:

// set arguments for WP_Query()
$args = array(
    'post_type' => 'my-custom-post-type',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

As you can see from these examples, we can add a random redirection link to a WordPress website with just a few lines of code. Nothing complicated, nothing too advanced.

random-redirection-wordpress-wikipedia-wikihow

If random redirection still doesn’t make sense to you, hop on over to Wikipedia and WikiHow and see how their links to random articles work.

Play The Randomization Game!

Now that you know how easy implementing a random redirection page in WordPress is, you can start planning for your own random output.

All in all, it’s a great feature. Every online magazine should have it. It requires only a single click per request; it’s unpredictable, it’s fun, and it will be useful to your readers.

Further Reading

Smashing Editorial (al)