Search code examples
phpwordpresswoocommercecartsku

Displaying the SKU in cart item names on WooCommerce cart page


I am showing SKU value with product title in cart page but right now each words SKU and product title getting linking separately.how can i show just single link rather then having linking separately.

for showing SKU value In cart page added this code in Functions.php

add_filter( 'woocommerce_cart_item_name', 'add_sku_in_cart', 20, 3);
function add_sku_in_cart( $title, $values, $cart_item_key ) {
$sku = $values['data']->get_sku();
$url = $values['data']->get_permalink( $product->ID );
$final='<a href="'. $url .'">SKU: '. $sku .'</a>';
return $title ?  sprintf("%s  - ", $final) .$title : $final;
}       

Example Right now showing this

<a href="http://localhost/test/?product=child-product">SKU: asda121 </a> - <a href="http://localhost/test/?product=child-product">Child Product</a>

but I want it like that

<a href="http://localhost/test/?product=child-product">SKU: asda121 - Child Product</a>                               

Solution

  • You should use your custom function hooked in woocommerce_cart_item_name filter hook this way, to get the same link on both Sku and item name (when sku exist):

    add_filter( 'woocommerce_cart_item_name', 'customizing_cart_item_name', 10, 3 );
    function customizing_cart_item_name( $item_name, $cart_item, $cart_item_key  ) {
    
        $product = $cart_item['data'];
        $sku = $product->get_sku();
    
        // When sku doesn't exist
        if(empty($sku)) return $item_name;
    
        $product_name = $product->get_name();
        $product_id = $product->get_id();
        $url = $product->get_permalink( $product_id );
    
        return '<a href="'. $url .'">Sku: ' . $sku . ' - ' .$product_name . '<a>';
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and works