skip to Main Content

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?

2

Answers


  1. You are almost there. You can do this by applying some basic conditioning.

    add_filter( 'woocommerce_cart_item_name', 'just_a_test', 10, 3 );
    function just_a_test( $item_name,  $cart_item,  $cart_item_key ) {
        $product_ids = array(68, 421);
        if(in_array($cart_item['product_id'], $product_ids) {
            echo $item_name.' ('.$cart_item['product_id'].')';
        } else {
            echo $item_name;
        }
    }
    

    Note that I’ve used an array of product ids incase that your problem may need this function to apply on two or more product ids. Alternatively, you can just use this:

    //single product id
    $product_id = 68;
    echo $item_name . ($cart_item['product_id'] == $product_id) ? ' ('.$cart_item['product_id'].')' : '';
    
    Login or Signup to reply.
  2. 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 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search