Search code examples
phpwordpresswoocommerceproductcart

Add the product ID after the cart item name in WooCommerce cart page for specific products


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 ONLY for a specific Product.

I'm looking at this code:

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 indeed returns the name with a product ID but it applies on all Products on my store.

Only want to display the product ID for a specified product. I'm curious how I'd go about doing this?


Solution

  • The answer, given by jpneey does not work (HTTP ERROR 500) because:

    • echo was used instead of return

    So you get:

    function filter_woocommerce_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
        // The targeted product ids, multiple product IDs can be entered, separated by a comma
        $targeted_ids = array( 30, 815 );
        
        // Product ID
        $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
        
        if ( in_array( $product_id, $targeted_ids ) ) {
            return $item_name . ' (' . $product_id . ')';
        }
    
        return $item_name;
    }
    add_filter( 'woocommerce_cart_item_name', 'filter_woocommerce_cart_item_name', 10, 3 );