Blog

Override WooCommerce Template File on your Plugin

The normal WooCommerce template loader searches the following locations in order, until a match is found:

your theme / template path / template name
your theme / template name
default path / template name

We’re going to alter this slightly by injecting a search for the template within our own custom plugin (step 3 below), before finally defaulting to the WooCommerce core templates directory:

your theme / template path / template name
your theme / template name
your plugin / woocommerce / template name
default path / template name

This can be done by adding the following function and filter, which basically duplicates and modifies the behavior of the woocommerce_locate_template() function found within woocommerce-core-functions.php:

 function myplugin_plugin_path() { 

// gets the absolute path to this plugin directory

return untrailingslashit( plugin_dir_path( __FILE__ ) );

}

add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 );

function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) {

global $woocommerce;

$_template = $template;

if ( ! $template_path ) $template_path = $woocommerce->template_url;

$plugin_path = myplugin_plugin_path() . '/woocommerce/';

// Look within passed path within the theme - this is priority

$template = locate_template(

array(

$template_path . $template_name,

$template_name

)

);

// Modification: Get the template from this plugin, if it exists

if ( ! $template && file_exists( $plugin_path . $template_name ) )

$template = $plugin_path . $template_name;

// Use default template

if ( ! $template )

$template = $_template;

// Return what we found

return $template;

}

With that active you can override core template files by placing them in myplugin/woocommerce/. For instance, to override loop/add-to-cart.php, copy that file to your plugin in the following location: myplugin/woocommerce/loop/add-to-cart.php and make your modifications. The theme will still be able to override it, and all other template files will be loaded from WooCommerce or the default path, as normal.

Comments (1)

Leave a Reply