Originally posted on my website on February 19th 2020
How to conditionally load a different/custom template file.
Adding custom template files for specific pages can easily be done in WordPress by using special file headers. I wrote an article about this a while back. But this will make these templates selectable in the WordPress admin for each page or post. Now if you have a single purpose template like a contact page, or if you need the template to change because of some other condition your better of using the template_include filter like shown in this snippet.
<?php | |
/** | |
* template_include_callback. | |
* | |
* Maybe redirect to a different template file | |
* | |
* @see https://since1979.dev/snippet-006-conditionally-loading-a-custom-template/ | |
* | |
* @uses is_page https://developer.wordpress.org/reference/functions/is_page/ | |
* @uses locate_template https://developer.wordpress.org/reference/functions/locate_template/ | |
* | |
* @param String $template The path of the template to include. | |
* @return String | |
*/ | |
function template_include_callback(String $template) | |
{ | |
if (is_page(148)) | |
return locate_template('contact.php'); | |
return $template; | |
} | |
/** | |
* Hook: template_include. | |
* | |
* @uses add_action() https://developer.wordpress.org/reference/functions/add_action/ | |
* @uses template_include https://developer.wordpress.org/reference/hooks/template_include/ | |
*/ | |
add_filter('template_include', 'template_include_callback', 100, 1); | |
?> | |
In the snippet above we add a filter to the template_include hook and register a callback function called template_include_callback.
Our new template_include_callback function receives a string containing the path to the currently selected template file and must return a path to a template file. In this example we determine if the current page is the contact page by checking the post id using the is_page function. If so we use the locate_template function to get a full path to the contact.php template file and return that path. if not we simply return the originaly selected template file.
Note: Checking for the post id is a bit crude but you can change this condition to whatever you need. You could check for tags, categories or maybe you have some Acf condition that needs a custom template.
Follow
Found this post helpful? Follow me on twitter @Vanaf1979 or here on Dev.to @Vanaf1979 to be notified about new articles, and other WordPress development related resources.
Thanks for reading
Top comments (0)