wc_get_template
is great for breaking up a complex plugin into simpler parts.
By default wc_get_template is designed to search in /wp-content/plugins/woocommerce
or /wp-content/themes/yourtheme/woocommerce
for a template – not in your plugin folder.
Editing wc_get_template with a filter
Luckily we can use a filter to edit the behavior of wc_get_template
to search in our plugin if its searching for a specific file path (e.g ‘templates/yourtemplate.php).
** A filter is essentially an array of functions the application will run through before returning a result.
First, add our own function to the filter.
// modify wc_get_template to search in plugin directory
add_filter('wc_get_template', 'gerrg_get_template', 10, 2);
Next we define the function which will modify the behavior of wc_get_template to search in our plugin folder. The function takes 5 parameters but we only need the first two:
- $located – the results of searching in the woocommerce folder (default behavior)
- $template_name – this is what we will use to set a condition in our gerrg_get_template function,
Lets write some code
The goal of this function will be to get wc_get_template
to search in our plugin directory instead of in the default woocommerce folder path.
function gerrg_get_template($located, $template_name) { // if we are searching for a specific file if ('path/to/my/template.php' === $template_name) { // return the path to that file return plugin_dir_path(__FILE__) . $template_name; } // otherwise work as normal return $located; }
The function is not too complicated – essentially we added a simple conditon to the wc_get_template function.
If wc_get_template is passed a SPECIFIC path (e.g. ‘path/to/my/template.php’) the function will return your plugin’s directory path to the file.
If the condition is not met, revert back to normal function (look in WC folder and theme’s WC folder).
Wrapping up
The filter modifies the functionality of wc_get_template
under very specific circumstances.
... if ('path/to/my/template.php' === $template_name){ return plugin_dir_path(__FILE__) . $template_name; } ...