Sometimes when developing a WooCommerce plugin you want to output a snippet of HTML, and do so in such a way that the content can be easily overridden by a theme. It’s part of the process of crafting a well-engineered, customizable plugin. The best way to achieve this is by using WooCommerce’s own templating mechanism, and what once took some effort and some filters is now a snap thanks to one of the recent WooCommerce releases (I tell ya, it just keeps getting better and better!) What we’ll be doing today is covering how to create a plugin with an included template file which can be overridden in a WordPress theme.
The Code
The first thing we need is the path to your plugin, which is easy enough to get via the plugin_dir_path()
method. I tend to follow WooCommerce’s lead and add a plugin_path()
method to my plugin class when needed:
function plugin_path() { if ( $this->plugin_path ) return $this->plugin_path; // gets the absolute path to this plugin directory return untrailingslashit( plugin_dir_path( __FILE__ ) ); }
Note this is of course assumed to be within a plugin class file, a practice I almost always follow when writing WordPress plugins. Doing so simplifies name space issues, and results in cleaner more professional-looking code in my opinion.
Next, lets create our template file, we’ll pretend it’s a snippet that will appear on the product listing page and we’ll call it product-doodad.php
. We’ll create it on the following path: your-theme/templates/single-product/product-doodad.php
, and it’ll have the following code for example:
<div id="doodad"><?php echo $doodad_content; ?></div>
Finally, include the template where needed in your plugin:
woocommerce_get_template( 'single-product/product-doodad.php', array( 'doodad_content' => $doodad_content ), '', $this->plugin_path() . '/templates/' );
Where the first argument is the template name, the second argument includes any parameters to pass to the template, the third argument (template path) is not used and defaults to ‘woocommerce’, and the fourth argument is the default path to the template (ie, the path to the one included with your plugin). As described by the signature comments for the woocommerce_locate_template()
method, this will result in a search within the following locations:
your theme / template path / template name
your theme / template name
default path / template name
So this template can be overridden in a theme by creating a file at yourtheme/woocommerce/single-product/product-doodad.php
.
Overriding a Core Template
For a solution to a slightly different problem see my article on overriding a WooCommerce core template file.