There are many WordPress plugins that allows you to provide your own template in your theme that overrides the default template (e.g. WooCommerce). I’d like to look at how you can add this functionality to your own plugin.
Default Template
For demonstration purposes I’ve created a WordPress plugin called the Raptor Button plugin.
This plugin has a built-in template at /templates/btn.php
that looks like
<?php
/**
* Default: Template for Raptor Button Plugin.
*
* Note: The trigger element must have the data-attribute
* data-fe-raptor="trigger"
*
* @var $btn_txt The text to display in the button.
*
* @package fe-raptor-button
*/
?>
<button data-fe-raptor="trigger">
<?php echo esc_html( $btn_txt ); ?>
</button>
in the plugin, we display this template with code like:
$btn_txt = 'Get Raptor';
$tmpl = __DIR__ . '/templates/btn.php';
include $tmpl;
Making the Template Overridable
Before displaying the default template that is part of the plugin, I want to check the theme folder for a custom template to use. We’ll designate /fe-raptor-button/btn.php
in our current theme as the location for an override file. (e.g. /wp-content/themes/bootstrap-genesis/fe-raptor-button/btn.php
).
// Set our template to be the override template in the theme.
$tmpl = get_stylesheet_directory() . '/fe-raptor-button/btn.php';
if ( ! file_exists( $tmpl ) ) {
// If the override template does NOT exist, fallback to the default template.
$tmpl = __DIR__ . '/templates/btn.php';
}
// Display the template.
include $tmpl;
Using Templates in a Shortcode
It is a little tricky to use a template in a WordPress shortcode but it can be done. The issue is a shortcode shouldn’t output anything, instead it returns a string with the markup to display. By default, using an include
for a template will output the contents of the template. We work around this by using output buffering.
Instead of
include $tmpl;
we do something like
ob_start();
include $tmpl;
$output = ob_get_clean();
return $output;
Implement In Your Own Plugins
I hope this information is helpful in creating overridable templates in your own plugins. In the comments, I’d love to hear about code you’ve written where you support using a custom template.
Image Credit
Flickr smokeygo
Heh! Thanks for the tips 🙂 I was looking to do this at one moment and had no clue on how I can do it!
Hey,
thank you for that awesome tutorial. It’s exactly what I was looking for.