Get in WooCommerce cart the product ID of a cart item

Kevin.a picture Kevin.a · Dec 12, 2016 · Viewed 36k times · Source
$cart_item = $woocommerce->cart->get_cart(); 

I have the above code.

if I run print_r on cart_item I get a multi dimensional array:

Array(    [a6292668b36ef412fa3c4102d1311a62] => Array        (            [product_id] => 6803

How do I get the product_id only?

I tried $test = $cart_item['data'];

print_r($test);

Didn't work.

Answer

LoicTheAztec picture LoicTheAztec · Dec 12, 2016

To get the product ID of each cart item in the foreach loop (for a simple product):

foreach( WC()->cart->get_cart() as $cart_item ){
    $product_id = $cart_item['product_id'];
}

If it's a variable product, to get the variation ID:

foreach( WC()->cart->get_cart() as $cart_item ){
    $variation_id = $cart_item['variation_id'];
}

Or for both cases (where $cart_item['data'] is the WC_Product Object in Woocommerce 3+):

foreach( WC()->cart->get_cart() as $cart_item ){
    // compatibility with WC +3
    if( version_compare( WC_VERSION, '3.0', '<' ) ){
        $product_id = $cart_item['data']->id; // Before version 3.0
    } else {
        $product_id = $cart_item['data']->get_id(); // For version 3 or more
    }
}

Update: Using Product ID outside the loop

1) Breaking the loop (Just to get the first item ID (product ID) of cart):

foreach( WC()->cart->get_cart() as $cart_item ){
    $product_id = $cart_item['product_id'];
    break;
}

You can use directly $product_id variable of the first item in cart.


2) Using an array of product IDs (one for each item in cart).

$products_ids_array = array();

foreach( WC()->cart->get_cart() as $cart_item ){
    $products_ids_array[] = $cart_item['product_id'];
}
  • To get the 1st item product ID: $products_ids_array[0];
  • To get the 2nd item product ID: $products_ids_array[1]; etc…

To check product categories or product tags in cart item use WordPress has_term() like:

foreach( WC()->cart->get_cart() as $cart_item ){
    // For product categories (term IDs, term slugs or term names)
    if( has_term( array('clothing','music'), 'product_cat', $cart_item['product_id'] ) ) {
        // DO SOMETHING
    }

    // For product Tags (term IDs, term slugs or term names)
    if( has_term( array('clothing','music'), 'product_tag', $cart_item['product_id'] ) ) {
        // DO SOMETHING ELSE
    }
}

We always use $cart_item['product_id'] as we get the parent variable product when a cart item is a product variation.

Product variations don't handle any custom taxonomy as product categories and product tags