Home » Hooks » template_include

The template_include hook is a powerful WordPress hook that allows developers to modify the template file used to display a particular page or post on a WordPress site. It gives you the ability to programmatically change the template file based on specific conditions, giving you complete control over the layout and design of your site.

When a request is made to display a page or post on a WordPress site, the template_include hook is triggered just before the template file is loaded. By hooking into this action, you can intercept the default template file and provide a custom template file instead. This can be useful in various scenarios, such as creating custom page templates for certain sections of your site, or dynamically changing the template based on user roles or other conditions.

One common use case for the template_include hook is creating custom page templates. For example, let’s say you have a custom post type called "Books" and you want to use a different template to display the single book pages. You can use the template_include hook to check if the current post is of the "Books" post type, and then load a custom template file specifically designed for book pages.

Here’s an example usage code that demonstrates how you can use the template_include hook to load a custom template file for the "Books" post type:

function custom_book_template($template) {
    if (is_singular('books')) {
        $new_template = locate_template(array('single-books.php'));
        if (!empty($new_template)) {
            return $new_template;
    return $template;
add_filter('template_include', 'custom_book_template');

In this example, we define a function called custom_book_template that checks if the current post is of the "Books" post type using the is_singular() function. If it is, we use the locate_template() function to locate the custom template file called single-books.php. If the custom template file is found, we return it, otherwise, we return the default template.

By adding the custom_book_template function as a filter to the template_include hook using the add_filter() function, we ensure that our custom template file is used when displaying single book pages.

Using the template_include hook gives you the flexibility to completely control the template files used in your WordPress site, allowing you to create unique designs and layouts tailored to your specific needs.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.