Woocommerce override cart template using custom plugin

To override cart template just go to your plugin directory and create templates directory in plugin root folder and copy your cart.php file from woocommerce and paste here in templates folder. Now the cart function will execute from your plugin. 

Here, we have created a folder name “template” in plugin directory to override cart functionality. Note: It will only override cart.php not cart-mini or other files from woocommerce cart directory.

//Customize cart.php from plugin
function dna_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', 'dna_locate_template', 10, 3 );

If you want to override whole woocommerce for customization then use below code and make changes as per your rquirements. Here in your custom plugin directory just create “woocommerce” folder and paste all woocommerce plugin template file in your directory.

// Override Woocommerce Templates from plugin start
// Override Template Part's (Files).
add_filter( 'wc_get_template_part',             'override_woocommerce_template_part', 1, 3 );
// Override Template's.
add_filter( 'woocommerce_locate_template',      'override_woocommerce_template', 10, 3 );

function override_woocommerce_template_part( $template, $slug, $name ) {
    $template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/woocommerce/';
    if ( $name ) {
        $path = $template_directory . "{$slug}-{$name}.php";
    } else {
        $path = $template_directory . "{$slug}.php";
    }
    return file_exists( $path ) ? $path : $template;
}

function override_woocommerce_template( $template, $template_name, $template_path ) {
    $template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/woocommerce/';
    $path = $template_directory . $template_name;
    return file_exists( $path ) ? $path : $template;
}

Sometimes we need to customize only cart image and title only not the template file. Then we can use below function to customize cart image. Below code customize cart image using plugin function.

//Customize cart image using plugin 
function custom_new_product_image( $_product_img, $cart_item, $cart_item_key ) {
      //Code to customize url and image
      echo $_product_img
}
add_filter( 'woocommerce_cart_item_thumbnail', 'custom_new_product_image', 10, 3 );

To customize cart title just add below code to your plugin.

//Customize cart title and link using function.php
function add_usr_custom_session($product_name, $cart_item, $cart_item_key ) {
  $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
  echo $_product->get_name();
}
add_filter('woocommerce_cart_item_name','add_usr_custom_session',10,3);

Leave a Reply