WordPress Tutorial: Template Redirects

Sometimes when developing with WordPress you may wish to redirect a user to a bespoke template that is different from the standard blog functionality of posts and archives. Maybe you want a certain view of content featuring a custom loop for displaying a combination of custom taxonomies and custom post types. Whatever the situation, WordPress makes it easy to redirect users to certain templates when specific conditions are met.

The example on this page uses URL matching to initiate the template redirect, so when a user visits a certain URL they will be viewing a custom template. Simply copy the following code into your theme's functions.php file:

//TEMPLATE REDIRECT
add_action ( 'template_redirect', 'jnorton_redirect' );
function jnorton_redirect() {
$url = explode ( "/", substr ( $_SERVER ['REQUEST_URI'], 1 ) );
if ($url [0] == 'test') {
include_once (get_theme_root().'/'.get_template().'/test.php');
exit;
}
}

To explain what is happening, the first line add_action ( 'template_redirect', 'jnorton_redirect' ); creates a new WordPress action (hook) that is registered within the WordPress database. The first line of the function named jnorton_redirect() create an array from the predefined PHP variable: $_SERVER['REQUEST_URI']. The next line checks to see if the browser has requested the URL named 'test'. If a match is found then the custom template file is included before the script exited.

Please note: this code does not allow WordPress to clean up after itself, database connections remain open, object are not destroyed, the list goes on. For a better technique to including custom templates within WordPress visit my article about efficiently including custom WordPress templates.