WordPress template_include Simple example


Example

This filter is very useful. One of the common problems for developers is how to include templates in plugins they develop.

The filter is applied immediately after wordpress locates the appropriate template in the active child/parent theme using the wp hierarchy.

Be careful to define when you want to modify the template path. In the below example, the code checks to see if the current page is the single view of our custom post type cpt.

Simple enough example to get started with!

add_filter('template_include', 'custom_function');


function custom_function($template){
    
    //change a single post template...
    
    if( is_singular('cpt')  ){
         $template= 'path/to/another/template_file';
    }
      
    
    return $template;

}