Download WooCommerce to cart item id

$cart_item = $woocommerce->cart->get_cart(); 

I have the code above.

If I run print_r on cart_item, I get a multidimensional array:

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

How do I get only product_id?

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

 print_r($test); 

Does not work.

+6
source share
1 answer

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

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

If this is 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:

 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 Out of Cycle

1) Cycle break (just to get the first product identifier (product identifier) ​​in the basket):

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

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


2 Using an array of product identifiers (one for each item in the basket).

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

Source: https://habr.com/ru/post/1013100/


All Articles