Is it possible to define a template for a custom post type within a plugin independent of the active theme?

I’m writing a plugin to manage data about open-source projects. I developed an object model and have successfully created all custom post types and taxonomies, as well as implemented the correct capabilities/roles using the Members plugin. The appropriate users can create, modify, and delete their own posts, and administrators can approve them, as well as modify and delete anyone’s posts.

My problem is, that I want to define the template for a single Project and for a list of Projects (single and archive, I believe – I’ve never worked with WordPress at this level), but I do not want The Loop to rely on the current theme to render the page for a single Project or a list of Projects. If I am using the TwentyTen theme, I want it to use my plugin’s template for those custom post types. If I am using the TwentyEleven theme, I still want it to use my plugin’s template for those custom post types.

I want this to obey the “it just works” paradigm, but right now users can’t just drop the folder in the plugin directory – they have to add the appropriate files to their theme folder every time they switch themes. I’ve checked out the template hierarchy and I have the filenames correct, but they aren’t used by WordPress if they are in the plugin folder, or in plugin/templates folder.

Thanks!

Solutions Collecting From Web of "Is it possible to define a template for a custom post type within a plugin independent of the active theme?"

You need to use the template_include filter which is the generic filter for all template inclusions.

add_filter( 'template_include', 'my_plugin_templates' );
function my_plugin_templates( $template ) {
    $post_types = array( 'project' );

    if ( is_post_type_archive( $post_types ) && ! file_exists( get_stylesheet_directory() . '/archive-project.php' ) )
        $template = 'path/to/list/template/in/plugin/folder.php';
    if ( is_singular( $post_types ) && ! file_exists( get_stylesheet_directory() . '/single-project.php' ) )
        $template = 'path/to/singular/template/in/plugin/folder.php';

    return $template;
}

I’ve not fully tested the post type archive bit, you may need to include a check using is_tax( $taxonomies ) to get it to work on associated custom taxonomy archives.