Skip to content

Instantly share code, notes, and snippets.

@wp-kitten
Last active July 21, 2018 09:30
Show Gist options
  • Save wp-kitten/e2d2a8588b5ce772162453204674c7ce to your computer and use it in GitHub Desktop.
Save wp-kitten/e2d2a8588b5ce772162453204674c7ce to your computer and use it in GitHub Desktop.
Override WooCommerce from plugin

https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment