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.
source share