In this tutorial, I’ll show you how we can override WooCommerce templates with code. We can use the code inside functions.php
of an active theme or even inside a plugin.
Normally, we override WooCommerce templates inside an active child theme. We create a folder named as “woocommerce” inside an active theme and we can create our templates there.
Sometimes there comes a situation when we gonna need to override WooCommerce templates with code depends on the condition. I mostly override WooCommerce templates with code if there is no child theme installed. In this scenario, I create custom plugin and override WooCommerce templates there.
To override WooCommerce templates with code, you can use the below code:
function shyk_locate_template( $template, $template_name, $template_path ){ $basename = basename( $template ); if( $basename == 'cart-item-data.php' ) { $template = trailingslashit( plugin_dir_path( FILE ) ) . 'templates/cart-item-data.php'; } if( $basename == 'cart.php' ) { $template = trailingslashit( plugin_dir_path( FILE ) ) . 'templates/cart.php'; } return $template; } add_filter( 'woocommerce_locate_template', 'shyk_locate_template', 10, 3 );
Ok what we are doing in the above code is we are checking basename of template, for example, if basename is cart-item-data.php
, then override the template with the one present in our plugin or you can use any other location if you added code in functions.php
. You can also use any other custom condition alongside basename.