Random Redirection In WordPress

Advertisement

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.

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 Redirect1 plugin first. Then you would probably try Random Redirect 22, 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 hierarchy3, 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()4 function, which has the post’s permalink as its input.

random-redirection-wordpress-add-random-page5
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-menu6
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_Query7 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-wikihow8

If random redirection still doesn’t make sense to you, hop on over to Wikipedia9 and WikiHow10 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

(al)

Footnotes

  1. 1 http://wordpress.org/extend/plugins/random-redirect/
  2. 2 http://wordpress.org/extend/plugins/random-redirect-2/
  3. 3 http://codex.wordpress.org/Template_Hierarchy#Page_display
  4. 4 http://codex.wordpress.org/Function_Reference/wp_redirect
  5. 5 http://www.smashingmagazine.com/wp-content/uploads/2012/04/random-redirection-wordpress-01.png
  6. 6 http://www.smashingmagazine.com/wp-content/uploads/2012/04/random-redirection-wordpress-02.png
  7. 7 http://codex.wordpress.org/Function_Reference/WP_Query
  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2012/04/random-redirection-wordpress-03.png
  9. 9 http://en.wikipedia.org/
  10. 10 http://www.wikihow.com/
  11. 11 http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/
  12. 12 http://wpguy.com/articles/how-to-make-a-random-post-button/
  13. 13 http://ottopress.com/2011/random-post-snippet/
  14. 14 http://wpsnipp.com/index.php/loop/redirect-home-page-to-a-random-blog-post/
  15. 15 http://codex.wordpress.org/Template_Tags/get_posts
  16. 16 http://codex.wordpress.org/Class_Reference/WP_Query

↑ Back to topShare on Twitter

Goce Mitevski is an independent designer and the founder of Nicer2. He's passionate about WordPress, Photography, 3D Visualization, Drawing, Illustration and Animation. When he's not designing, he's working on Contest Watchers.

Advertising
  1. 1

    Nice tutorial regarding wordpress in general but other then that this seems like a hack! Getting random rows out of larger database tables in mysql is rearly an easy task, at least if your concerned about the memory usage.

    Having a note in the article mentioning that this isn’t a great solution for larger websites would be appropriate.

    Other then that.. great article!

    0
  2. 2

    Nice article.I really happy to read this.Great stuff.

    0
  3. 3

    Christopher Ross

    April 20, 2012 3:25 am

    Goce, this is a great tutorial but there’s no reason to go through the hassle of creating a redirect page. Instead, use a hook and save yourself (and your users) the frustration of messing with templates / pages.

    add_action( ‘template_redirect’,’thisismyurl_random_post’ );
    function thisismyurl_random_post() {
    if ( $_SERVER[‘REQUEST_URI’] == ‘/random-post’ ) {
    foreach ( get_posts ( array( ‘numberposts’ => 1, ‘orderby’ => ‘rand’ ) ) as $post ) {
    wp_redirect ( get_permalink ( $post->ID ) , 302 );
    exit;
    }
    }
    }

    What this piece of code does is intercepts the page load before anything is sent, discovers that the client is loading a url with the random-post slug and then executes the random logic.

    Simply place that little bit of logic in your functions.php file and you’re all set.

    0
    • 4

      Thanks Christopher! That’s another legitimate solution, though I’m not sure if it plays nice with caching plugins such as W3 Total Cache.

      0
    • 5

      This is similar to the method I described here: http://ottopress.com/2011/random-post-snippet/

      Difference: Using a 307 is slightly safer with some older browsers due to their weird caching behavior. Also, I use a rewrite rule to give it a pretty URL within the hierarchy instead of checking the SERVER variable directly.

      0
  4. 6

    yay random article? The next up is “related article”.

    How about linking text from the current article to relevant articles.
    – This is good because you are linking from an article the reader thinks is relevant, to another article that should be related.
    – This is good for SEO.
    – Did I mention it is good because it is relevant to the current article? I will just again in case.

    The relevance is the main point here, a random article may have nothing to do with what the visitor is reading. Will they read it? Maybe. Will they read something similar? Yes.

    If you don’t have the time to place 2-3 links in each article you should probably find another business to be in.

    0
  5. 7

    Great article, thanx.

    0
  6. 8

    Nice article, Goce. I’ve been noticing in Google Analytics that the Archive pages on my sites don’t get that many page views so I’ve been wondering whether to get rid of them or try something else. This sounds like an interesting idea so I’ll give it a try and see how it goes, thanks! :)

    0
    • 9

      You need to get them crawled. Cross referencing them via “Random articles” would work. Cross referencing them to posts with similar content would work better.

      Put the time in and manually do it.

      0
  7. 10

    nice post, also might put an example using ajax ;)

    0
  8. 11

    “‘orderby’ => ‘rand'” on a large site could really cause performance problems. It’s far better to get a count of published items, then pick a number at random up to that limit, then select that item only. This method is far better on performance as it only generates one random value, not a random value for every record.

    0
    • 12

      You could cache it, so not a huge problem.

      The bigger problem is that random articles are not super useful for SEO. As an example it would be much better to link a photoshop brush tutorial to three other photoshop/brush tutorials rather than a HTML5 tutorial.

      0
  9. 13

    Hey Goce, nice article! :)

    0
  10. 14

    I think the idea is great, but the mentioned executions are far too much oldschool.

    Why not just provide a simple widget that gets one random article and displays the Title & Proper link to it.
    This way people can click it if it interests them. Rather then forcing them to click a link.

    Besides, just because an archive is not useful to most people. Doesn’t mean you don’t have to provide one. I’m definitely not going to click a random article link If I don’t know where it will take me.
    My time is more valuable then that.

    How about providing filter based search for all articles. So you can see everything from before a time, based on categories or tags.. etc.

    0
  11. 15

    Great article! Thanks for the tips!

    0
  12. 16

    Great idea, thanks.
    But in my blog I suggest user to view posts from interesting categories by placing a random quote block linked to the full article in the sidebar. And if they aren’t follow I don’t insist.

    0
  13. 17

    How i can redirect pages of my wp blog http://www.a2zcareerinfo.com to categories. Is there any plugin for the same, plz notify me by mail.

    Thanks

    0
  14. 18

    For SEO purposes, the redirect should be done with a 307 code, like so:

    wp_redirect( get_permalink(), 307 );

    This will let search bots know that it’s a temporary redirect.

    0
  15. 19

    Is it possible to somehow cycle through articles, so that first article can again appear only once all articles have been cycled?

    0
  16. 20

    Konstantin Kovshenin

    April 30, 2012 7:48 am

    Hi there! Please don’s use numberposts, use posts_per_page instead. Also, get_posts is simply a wrapper over WP_Query, so it doesn’t really matter which you use, both of them are essentially the same.

    The foreach and while loops are really confusing, why are you looping in the first place? You’re fetching one single post, just check for its existence with if ( have_posts() ) or if ( $my_random_post ). Also consider using wp_safe_redirect instead of wp_redirect.

    One last thing, you should have mentioned, that this won’t work with a page caching plugin. You’ll have to specify some exceptions in the plugin to ignore your random URL.

    Cheers,
    ~ K

    0
    • 21

      Just a question, this used to work fine when I first did it on Chrome many mhntos ago, but now when I do it when I changed my URL once again, the screen stays white instead of redirecting. But in Firefox it redirects. Am I the only one with this problem? :S How do I fix it so that it redirects on Chrome as well?[]Mr. Tumblr Reply:February 23rd, 2012 at 3:03 pmWhy don’t you try clearing Chrome’s cache?. Have you tested the tumblr redirect on Internet Explorer, Safari and Opera as well?[]

      0
  17. 22

    i have a wordpress blog and these days i am having issue with random redirection of my home page.. I have set site meter and statcounter login.. Both of them shows exit links from my home page . People just navigate to my home page and they are carried out to thes spam links. but these spam links are not visible and i tried to remove them .. but i cant find any..
    These spam links are total 5 and hosted on a same shared ip .. content wise similar to my site.. they hijack my visitors to my site.. any help please ??

    0
  18. 23

    Nice post! But it is not working with a lot of themes. For me it only works with the standard WP – Theme!
    I also cant find random-page.php in the WordPress template hierarchy. Did they change it?

    0
  19. 24

    Can someone in some manner circuit by way of content, to ensure initial write-up could yet again look one time most content are actually cycled?
    Click grandmasdessertsdiary.com/ for more information.

    0
  20. 25

    To make a random link in wordpress, now you can simply put: /?random inside a hyperlink and that works. Soooooo much easier than the rest.

    0
  21. 26

    Oh that /?random does require that Random Post Link plugin be installed, my bad.

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top