I’m in the midst of building a WordPress Plugin that adds a custom post type, for which I’d like to include a default template to display. Essentially, this is an event management plugin, and the custom post type is for the Events. There’s a handful of custom meta fields, as well as a child post type (Performances), so without a default template to display them, using it would be pretty unfriendly. But I would like theme designers to be able to create their own templates for these post types if desired.
Is there a way to use the the template provided with my plugin unless the theme provides its own template? What’s the best practice for doing so?
Edit:
Following the advice of Peter Rowell, I caught the template_redirect action and, if the post type was one of mine and a template for it did not exist in the current theme, defaulted to the plugin’s template:
class FestivityTemplates {
public static function determineTemplate(){
global $post;
$standard_type = strpos($post->post_type, 'fest_');
if(is_single() && $standard_type !== false) {
FestivityTemplates::loadSingleTemplate($post);
}
}
private static function loadSingleTemplate($post) {
$template_name="single-".$post->post_type.'.php';
$template = locate_template(array($template_name), true);
if(empty($template)) {
include(WP_PLUGIN_DIR . '/Festivity/lib/templates/' . $template_name);
exit();
}
}
}
add_action('template_redirect', array('FestivityTemplates', 'determineTemplate'));
3 Answers
You might want to look at the routine that WP uses for this: locate_template()
. It is in wp-includes/theme.php
and is called from a number of functions in that file. Those functions are used by wp-includes/template-loader.php
to select the correct type of template based on the current page and then walk up the theme hierarchy looking for a match.