Custom Taxonomy in plugin and template

First of all – plugins are for generating content, themes are for displaying it. So really, a plugin shouldn’t do this. But there are grey areas – for example in an ‘events’ related plugin, it would be desirable to display dates, venue etc – things that a WordPress theme wouldn’t normally display.

I would suggest

  • making the plugin templates over-rideable with templates of the same name in the theme/child theme.
  • Being able to ‘turn off’ plugin forcing of the template.

To alter the template being used you can use the template_include filter. This is an example for taxonomy templates, but a similar process is possible for custom post types.

add_filter('template_include', 'wpse50201_set_template');
function wpse50201_set_template( $template ){

    //Add option for plugin to turn this off? If so just return $template

    //Check if the taxonomy is being viewed 
    //Suggested: check also if the current template is 'suitable'

    if( is_tax('event-venue') && !wpse50201_is_template($template))
        $template = plugin_dir_url(__FILE__ ).'templates/taxonomy-event-venue.php';

    return $template;
}

Note it assumes that the plugin templates are in a template sub-folder relative to current director.

Logic

This simply checks that the ‘event-venue’ taxonomy is being viewed. If not it will use the original template.

The wpse50201_is_template function will check if the template WordPress has picked from the theme/child-theme is called taxonomy-event-venue.php or taxonomy-event-venue-{term-slug}.php. If it is – the original template will be used.

This allows users of your plugin to copy them into their theme and edit them, and the plugin will prioritize the theme/child-theme templates. Only if it can’t find them does it fall back to the plug-in templates.

function wpse50201_is_template( $template_path ){

    //Get template name
    $template = basename($template_path);

    //Check if template is taxonomy-event-venue.php
    //Check if template is taxonomy-event-venue-{term-slug}.php
    if( 1 == preg_match('/^taxonomy-event-venue((-(\S*))?).php/',$template) )
         return true;

    return false;
}

I’ve used this method in a plugin – you can see a working example of the above here.

Leave a Comment