Include custom post type single template, but respect theme override of template if it exists

Through a plugin, I have created a custom post type named “my_custom”.

Also through the plugin, I am successfully including a template for the display of a “single” item of my custom post type:

function get_single_custom_template( $single_template ) {
    global $post;

    if ( 'my_custom' === $post->post_type ) {
            $single_template = PLUGIN_TEMPLATE_DIR . 'default-custom-single.php';
    }

    return $single_template;
}
add_filter( 'single_template', 'get_single_custom_template' ); 

This works as expected: my default-custom-single.php is displayed for a single entry of “my_custom” post type.

However, I want to be able to allow themes to override my default, and create their own template if desired.

How do I check whether there is a pre-existing custom-single.php in a theme and ONLY add my plugin-provided template if it doesn’t exist?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use locate_template() first. If this returns anything but an empty string '' then the template exists either in parent or child theme.

if( '' === locate_template( 'custom-single.php' ) ) {
    // Replace given template with your template path.
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x