You might want to override a WooCommerce core template file in your plugin rather than in the theme directory to future proof theme switching. WooCommerce searches the following locations in this order until a match is found. Let’s alter this slightly so that it searches out plugin folder in order to override the WooCommerce template.
- your theme / template path / template name
- your theme / template name
- your plugin / woocommerce / template name
- default path / template name
We can override WooCommerce templates by adding the following function and filter. This basically duplicates and modifies the behavior of the woocommerce_locate_template() function found within woocommerce-core-functions.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
function es_plugin_path() { // gets the absolute path to this plugin directory return untrailingslashit( plugin_dir_path( __FILE__ ) ); } add_filter( 'woocommerce_locate_template', 'es_woocommerce_locate_template', 10, 3 ); function es_woocommerce_locate_template( $template, $template_name, $template_path ) { global $woocommerce; $_template = $template; if ( ! $template_path ) $template_path = $woocommerce->template_url; $plugin_path = es_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; } |