Search code examples
phpwordpresswoocommercecarthook-woocommerce

Add the product ID after the cart item name in Woocommerce cart page


I'm looking to hook into the 'woocommerce_cart_item_name' filter in woocommerce and would like to display the product ID after the name. I'm working with this so far...

add_filter( 'woocommerce_cart_item_name', 'justatest' );

function justatest( $productname ) {
    echo $productname;
    // ideally echo name and product id here instead
}

This returns the name with a link around it but I want to add the actual ID of the product after the item name.

How can I add the product ID after the cart item name in Woocommerce cart page?

I know I'd need to not return first since that will pull me out of the function, but I'm curious how I'd go about doing this.


Solution

  • There are some missing arguments in your hooked function and you should need to make some changes to get the product Id this way:

    add_filter( 'woocommerce_cart_item_name', 'just_a_test', 10, 3 );
    function just_a_test( $item_name,  $cart_item,  $cart_item_key ) {
        // Display name and product id here instead
        echo $item_name.' ('.$cart_item['product_id'].')';
    }
    

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

    Tested and works.