Categories: How To // Wordpress

Load A Different Template

Do you want to include a custom template when some condition is true? Say no more, there is an filter hook called template_include.

It is really simple, call the filter hook, check if the condition is true and return the full path to the new template file.

I think that this is quite a useful filter. For example, let’s say that you have users with different roles. You could simply include a different template for each role on the same page. Or you have different user permissions and if user doesn’t have the correct permission, show a different template. Sweet right?

For some fun, let’s show a different template for administrators and other users.

function lessthanweb_custom_template( $template = '' ) {
	if ( current_user_can( 'manage_options' ) ) {
		//	This is just to demonstrate the template change.
		//	Use proper hooks to locate the template.
		$admin_template = plugin_dir_path( __FILE__ ) . 'admin-template.php';
		//	If template found, use it!
		if ( $admin_template != '' ) {
			return $admin_template ;

	return $template;
//	Execute filter as late as possible so we set a high number like 99.
add_filter( 'template_include', 'lessthanweb_custom_template', 99 );

admin-template.php is just a blank file with some text and you can find it in the GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *