About Christopher Ross

WordPress website developer with a passion for family, travel, talking and photography.

Random Post WordPress Redirection

This morning I came across a fantastic post on Smashing Magazine dealing with WordPress redirection and how to create a random redirect for visitors to your website. The post is absolutely correct in its method for creating a redirect as presented but there’s a slightly more elegant approach I’ve learnt with building newspaper websites with WordPress, and that’s to use a hook.

A hook is a means in WordPress to override the default functionality of WordPress and in this case, what we want to do is force WordPress to redirect before it’s even begun loading all the extra logic. To do that, we’ll tap into the template_redirect function. This function loads immediately after the website is initiated but before the theme file is loaded. It’s a perfect place to do things like redirect a page or, (as the name implies) the template. For example if you want to override a post or page template, this is where you can do it.

I’ve made two other small edits to the Smashing code example. First, I’ve added the redirect 302 value to the wp_redirect() function to tell Google that this is a temporary redirect (301 would be permanent) and I’ve combined the array for get_posts() into a single line as we won’t be reusing the variable.

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

}
}

Simply place this bit of logic in your functions.php file and you’ll be able to randomly redirect people to articles using a URL such as http://thisismyurl.com/random-post

What’s the Fastest, Cheapest Way to Get a Great Website?

Let’s pretend for a minute that you’re broke (or near broke) but you still want a good website for your small business. You can hire a website designer like me to build your site but it’s not going to come cheap (quality never does), you can learn to build your website yourself (that’ll take weeks to get a basic site up), or you can settle for something that looks bad. Continue reading