Setting a Template File for Custom Post Type from the Plugin in WordPress

If you want to set a template file for custom post type from the plugin instead of the theme root directory you are in the right place. WordPress has a filter hook called single_template which can be used for setting the custom post template file. So let’s get started!

Please go to your plugin toolkit file and copy and paste the below code in the file.

function your_cpt_custom_template( $file ) {

    global $post;

    /* Checks for single template by post type */
    if( "cpt" == $post->post_type ) { // here 'cpt' is your custom post type
        $file_path = plugin_dir_path(__FILE__) . "single-cpt.php";
        $file = $file_path;

    return $file;

/* Filter the single_template with your custom function*/
add_filter('single_template', 'your_cpt_custom_template');

Note: Please put your single-cpt.php file inside the plugin toolkit folder. Here, the file name of single-cpt.php can be anything you want

That’s it. If you have any query then please let me know in the comments section.

Happy coding. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *