WordPress Tutorial: Safely Include Custom Templates

Following on from my previous WordPress tutorial relating to template redirects, this article features a different technique to include custom templates within your WordPress website that is more efficient than doing a template redirect.

add_filter('template_include', 'jnorton_template_include');
function jnorton_template_include($incFile) {
$url = explode( "/", substr( $_SERVER ['REQUEST_URI'], 1 ) );
if ($url [0] == 'test') {
$file = get_theme_root().'/'.get_template().'/test.php'; if (file_exists($file)) {
$incFile = $file;
} else {
$wp_query->is_404 = true;
}
}
return $incFile;
} 

To briefly explain the code features an if statement to check if the browser has requested the URL named 'test'. If a match is found then the local system path and file name of the template file is returned to WordPress to use with the template_include filter.

The core filter is found in the file: wp-includes/template-loader.php and features the following code:

if ( $template = apply_filters( 'template_include', $template ) ) include( $template ); return; 

Looking at the core code you will see that there is a very simple if statement and standard PHP include to the file defined in your custom template_include filter.

Using a custom template_include filter to include template files allows WordPress to clean up after itself by closing database connections, destroying objects, etc. This means your website will be in great shape and will perform better under heavy load.