Overridable Templates in Your WordPress/ WooCommerce Plugin

Overridable Templates, Overridable Templates in Your WordPress/ WooCommerce Plugin, WP Devs

There are many WordPress/WooCommerce plugins that allow 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 WP Button plugin.
This plugin has a built-in template at /templates/btn.php that looks like

* Default: Template for WP Button Plugin.
* Note: The trigger element must have the data-attribute
* data-wp-devs=”trigger”
* @var $btn_txt The text to display in the button.
* @package wp-devs-button

<button data-wp-dev=”trigger”>
<?php echo esc_html( $btn_txt ); ?>
in the plugin, we display this template with code like:

$btn_txt = ‘Get WP’;
$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 /wp-devs-button/btn.php in our current theme as the location for an override file. (e.g. /wp-content/themes/bootstrap-genesis/wp-devs-button/btn.php).

// Set our template to be the override template in the theme.
$tmpl = get_stylesheet_directory() . ‘/wp-devs-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;

Apply the code something like

include $tmpl;
$output = ob_get_clean();
return $output;

Implement In Your Own Plugins

We hope this information is helpful in creating overridable templates in your own plugins. If you are looking for any kind of plugin development, customization, or want to fix any issue in your existing store/website we are really happy to help you.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *