Load custom single post template from plugin

Following snippet can be used for loading custom single post template for any custom post type from the plugin directory.

How use this snippet?

Replace books with your custom posts name and replace template/single-books.php with your template name & location.

Where this snippet can be used?

This snippet can be used mainly when you are creating custom plugin and you need a custom single post template for the newly created post type.

//custom single post template for custom posts
function load_custom_template($template) {
    global $post;
    if ($post->post_type == "books" && $template !== locate_template(array("single-books.php"))){
        $template = plugin_dir_path( __FILE__ ) . "template/single-books.php";
    return $template;
add_filter('single_template', 'load_custom_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