WordPress template_include More Adv example


Example

add_filter('template_include', 'custom_function');


function custom_function($template){
    
    /*
    *     This example is a little more advanced. 
    *    It will check to see if $template contains our post-type in the path.
    *    If it does, the theme contains a high level template e.g. single-cpt.php
    *    If not we look in the plugin parent folder for the file. e.g. single-cpt.php
    */
    
  
    //check to see if the post type is in the filename (high priority file)
    //return template if it is!
    
    global $post;
   
    if( strpos($template, 'single-'.$post->post_type.'php' ) !== false && strpos($template, 'archive-'.$post->post_type.'php' ) !== false ){
        return $template;
    }
    
    $plugin_path = 'var/etc/wp-content/plugins/plugin'; //include own logic here...
    
    if( is_singular($post->post_type) && file_exists($plugin_path.'/single-'.$post->post_type.'.php')   ){
         $template= $plugin_path.'/single-'.$post->post_type.'.php';
    } elseif ( is_archive($post->post_type) && file_exists($plugin_path.'/archive-'.$post->post_type.'.php') ) {
         $template= $plugin_path.'/archive-'.$post->post_type.'.php';
    } 
      
    return $template;
}