WooCommerce Templates
WooCommerce has templates for everything including emails and provides developers an easy way override them.
This template can be overridden by copying it to yourtheme/woocommerce/archive-product.php.
This is very useful when you build a custom or a child theme and you want to modify the way WooCommerce looks according to your needs.
But in some cases you need to do this with a plugin.
When to use a plugin
Let’ look at some real life scenarios.
- You don’t have ftp, ssh or any access to the site files.
- Maybe you don’t have child theme and you don’t want to loose changes when you update the parent theme.
- You want to build a plugin which needs to modify WooCommerce.
How to do it
To override WooCommerce templates wit a plugin, we can use the ‘wc_get_template’ filter. It takes a few arguments, but we will need only 2.
$located – the path to the new template file
$template_name – the name (and directory) of the template we are overriding.
Let’s override 2 templates – the archive product and new order email.
1 2 3 4 5 6 7 8 9 10 11 12 |
function re_wp_override_woo_templates( $located, $template_name ) { if( $template_name == ‘archive-product.php’ ) { $located = plugin_dir_path( __FILE__ ) . ‘templates/re-wp-archive-product.php’; } elseif( $template_name == ’emails/admin-new-order.php’ ) { $located = plugin_dir_path( __FILE__ ) . ‘templates/re-wp-new-order.php’; } return $located; } add_filter( ‘wc_get_template’, ‘re_wp_override_woo_templates’, 10, 2 ); |
Code explanation
We created a ‘templates’ directory in our plugin containing the files re-wp-archive-product.php and re-wp-new-order.php.
$template_name returns the name of the WC template. In this case archive-product.php which is located in woocommerce/templates and admin-new-order.php which is in woocommerce/templates/emails. As a result, WooCommerce loads them from our custom directory.