WordPress   

Load custom post templates from a plugin directory

This post has all the required snippets for including custom templates for post archive, taxonomy archive, single post, search archive etc. All these snippets are for loading these custom templates from the plugin directory but you can easily customize these snippets according to your own requirements.

Load custom post archive template.

add_filter( 'archive_template', 'load_custom_template' ) ;
function load_custom_template( $archive_template ) {
     global $post;
     if (is_archive() && get_post_type($post) == 'movies') {
        $archive_template = plugin_dir_path( __FILE__ ) . "templates/archive/archive-movies.php";
     }
     return $archive_template;
}

Load custom taxonomy archive template for single taxonomy

add_filter('template_include', 'tax_template_single_taxonomy');
function tax_template_single_taxonomy( $template ){
    global $post;
    if( is_tax('movies')){
        $template = plugin_dir_path( __FILE__ ) . "templates/archive/taxonomy-movies.php";
    }  
    return $template;
}

Load custom taxonomy archive template for specific taxonomies 

add_filter('template_include', 'tax_template_multiple_taxonomies');
function tax_template_multiple_taxonomies( $template ){
    global $post;
    if( is_tax(array('movies','songs'))){
        $template = plugin_dir_path( __FILE__ ) . "templates/archive/taxonomy-movies-songs.php";
    }  
    return $template;
}

Load custom single post template for custom post type

function custom_single_post_template($template) {
    global $post;
    if ($post->post_type == "movies" && $template !== locate_template(array("single-movies.php"))){

        $template = return plugin_dir_path( __FILE__ ) . "templates/single/single-movies.php";
    }
    return $template;
}
add_filter('single_template', 'custom_single_post_template'); 
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us