Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

My custom plugin creates a custom post type, and I want to theme my own "single-my_custom_cpt.php" file. However, I want to store it in my plugin folder, and allow that it be over-written in the websites' active theme folder.

For example, single-my_custom_cpt.php exists in /plugins/my-plugin/ folder, and someone creates /themes/site-theme/single-my_custom_cpt.php. I want the theme file to come up first, and if it's deleted, the plugin file to come up.

share|improve this question
1  
possible duplicate of Custom Taxonomy in plugin and template –  Stephen Harris Jul 3 '12 at 14:43
2  
You might also find these questions helpful too: wordpress.stackexchange.com/questions/51038/… wordpress.stackexchange.com/questions/55770/… –  Stephen Harris Jul 3 '12 at 14:44
1  
@willbeeler Please use the edit buttons for code styling, etc. We appreciate that you will try to take the same effort asking questions and formatting them properly as we take when answering them. Thanks. –  kaiser Jul 3 '12 at 15:17
    
Sorry about that Kaiser, I will. Thanks! –  willbeeler Jul 3 '12 at 17:57
    
+1 on Stephen's links. Helped me quite a lot when I began working on that. –  Zach Nov 7 '12 at 20:49

1 Answer 1

up vote 5 down vote accepted

To provide a default template that can be overwritten by a theme hook into template_include like the linked questions suggest. You get the template WordPress wants to use as a parameter. If that is not the file you want – replace it with your plugin’s file:

add_filter( 'template_include', 'wpse_57232_render_cpt', 100 );

/**
 * Provide fall back template file for a custom post type single view.
 *
 * @return void
 */
function wpse_57232_render_cpt( $template )
{
    // Our custom post type.
    $post_type = 'my_custom_cpt';

    // WordPress has already found the correct template in the theme.
    if ( FALSE !== strpos( $template, "/single-$post_type.php" ) )
    {
        // return the template in theme  
        return $template;
    }

    // Send our plugin file.
    if ( is_singular() && $post_type === get_post_type( $GLOBALS['post'] ) )
    {
        // return plugin file
        return dirname( __FILE__ ) . "/single-$post_type.php";
    }

    // Not our post type single view.
    return $template;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.