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
