Override WooCommerce template from your plugin

sergey zolkin 21234 unsplash

While doing some custom work for a client, I found that I needed to override a WooCommerce template from within a plugin. The client wanted to add some additional columns to the cart table and, as the WooCommerce cart.php template is not as hookable as most of the rest of WooCommerce, the only option was to override the template.

The normal way to do this is to include your new template file in the child theme. Usually this would be absolutely fine but in this instance the client wasn’t using a child theme and switching to one would have meant laboriously updating the theme settings. So the alternative was to include a version of cart.php within the plugin I was developing.

* Filter the cart template path to use our cart.php template instead of the theme's
function csp_locate_template( $template, $template_name, $template_path ) {
$basename = basename( $template );
if( $basename == 'cart.php' ) {
$template = trailingslashit( plugin_dir_path( __FILE__ ) ) . 'templates/cart.php';
return $template;
add_filter( 'woocommerce_locate_template', 'csp_locate_template', 10, 3 );

All we do is use the woocommerce_locate_template filter, check the name of the template – in this case cart.php – and replace the template path with a path to our own file.

Note that this code uses plugin_dir_path( __FILE__ ) to generate the path to the file, so you’ll need to fire this function from the plugin’s root directory.

One comment

  1. User image

    Thank you!
    This helps me a lot.

    I found a generic way for my project:

    * Plugin dir
    define('IRM_WOOCOMMERCE_VARIATION_SWATCHER_DIR', plugin_dir_path( __FILE__ ));

    * Override WooCommerce templates from your plugin with child theme way
    function irm_woo_locate_template( $template, $template_name, $template_path ) {
    $re = '/woocommerce\/(templates\/)?(.*)/m';
    preg_match($re, $template, $matches);
    if(isset($matches[2]) && !empty($matches[2]) && file_exists( IRM_WOOCOMMERCE_VARIATION_SWATCHER_DIR . 'woocommerce/' . $matches[2] )) {
    $template = IRM_WOOCOMMERCE_VARIATION_SWATCHER_DIR . 'woocommerce/' . $matches[2];
    return $template;
    add_filter( 'woocommerce_locate_template', 'irm_woo_locate_template', 10, 3 );

    After that, you could use [the official way](https://docs.woocommerce.com/document/template-structure/).

    Of course your way more optimal for the best performance.
    No doubt of that.

Leave a Reply

Your email address will not be published. All fields are required.