{"id":857,"date":"2012-09-12T10:31:10","date_gmt":"2012-09-12T20:31:10","guid":{"rendered":"http:\/\/mymonkeydo.com\/?p=857"},"modified":"2012-09-12T10:31:10","modified_gmt":"2012-09-12T20:31:10","slug":"custom-post-type-templates-in-plugins","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/custom-post-type-templates-in-plugins\/","title":{"rendered":"Custom Post Type Templates in Plugins"},"content":{"rendered":"
Problem<\/p>\n
I made a plugin that created a custom post type, but the only way I could customize the single-customposttype.php and archive-customposttype.php is by placing the files into the theme. \u00a0It would be nice if everythere could be contained in the plugin and the theme could override if needed.<\/p>\n
Solution<\/p>\n
WordPress to the rescue… There is a filter called ‘template_include’ that can be used to set the template. \u00a0It’s a general filter so you’ll need to check for your post type.<\/p>\n
add_filter( 'template_include', 'my_plugin_templates' );\nfunction my_plugin_templates( $template ) {\n\u00a0 \u00a0 $post_types = array( 'project' );\n\n\u00a0 \u00a0 if ( is_post_type_archive( $post_types ) && ! file_exists( get_stylesheet_directory() . '\/archive-project.php' ) )\n\u00a0 \u00a0 \u00a0 \u00a0 $template = 'path\/to\/list\/template\/in\/plugin\/folder.php';\n\u00a0 \u00a0 if ( is_singular( $post_types ) && ! file_exists( get_stylesheet_directory() . '\/single-project.php' ) )\n\u00a0 \u00a0 \u00a0 \u00a0 $template = 'path\/to\/singular\/template\/in\/plugin\/folder.php';\n\n\u00a0 \u00a0 return $template;\n}<\/code><\/pre>\n