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.

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.

Comments?

If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.

Follow me on twitter @Vanaf1979 or Dev.to @Vanaf1979 or subscribe to my newsletter to be notified about new articles, and other WordPress development related resources.

Thanks for reading

Tags: ,