Question

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?

Was it helpful?

Solution

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.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top