Overriding Woocommerce templates is easy if you are changing it for your theme but requires a little more work if a plugin needs to do this.
Back in December, Tom McFarlin wrote about copying a Woocommerce template file from a plugin into the theme directory. He acknowledges that it won’t always work e.g. file permissions or server-level security permissions. I immediately felt that there would be a way to make it work without copying the file from the plugin directory.
The typical way to override template files
Similar to using a child theme to override parent theme files, Woocommerce template files can be overridden by copying the required file(s) into the theme directory. This is ideal if your theme needs to override a file but not if you have a plugin that needs to do so – achieving this requires a little more work. NOTE: You should avoid editing template files as they are frequently updated and this can lead to a maintenance nightmare. Use hooks if at all possible.
In most cases you can change the behaviour of Woocommerce by making use of the extensive hooks available throughout the plugin but some changes require copying the relevant template file.
For example, on the My Account Dashboard page, if we want to change the “Hello” or “From your account…” sentences you will need to edit a copy of the template file. If you are making the change for your current theme then you can copy wp-content/woocommerce/templates/myaccount/dashboard.php to wp-content/THEMENAME/woocommerce/myaccount/dashboard.php.
If you have a plugin that needs to modify the file (where you would not be able to add files to the theme) you need to use another method.
Finding the right hook
I searched the Woocommerce source for ‘dashboard.php‘ and found it in includes/wc-template-functions.php as a parameter to a wc_get_template() call. I then looked at the code for wc_get_template() (in includes/wc-core-functions.php). There I saw the ‘wc_get_template‘ filter, with a helpful comment above it (‘Allow 3rd party plugin filter template file from their plugin.’).
Experimenting and Coding
I did a few experiments with the filter, using error_log() to see the data being sent to the filter function. I made a copy of the dashboard.php file, renaming it to my-dashboard.php to demonstrate that the filename can be changed. I changed ‘From your account‘ to ‘From THIS account‘ as an easy way to confirm that the overriding worked.
Then I wrote the filter function to use the plugin’s ‘my-dashboard.php‘ template file instead of the default ‘dashboard.php‘ file:
Before and After
The original My Account Dashboard page looks like:
The modified version looks like (I added the orange line to the screenshot):
There is always the risk that the theme will be overriding the same file. In that case the function should compare the $template_path and $default_path parameters and decide whether to use the plugin version.
Leave a Reply