使用此代码:
foreach ( WC()->cart->get_cart() as $cart_item ) {
$quantity = $cart_item['quantity'];
echo $quantity;
}
我可以获得购物车中添加的所有产品的数量,但我需要特定产品.
解决方法:
你应该试试这个:
// Set here your product ID
$targeted_id = 24;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if($cart_item['product_id'] == $targeted_id ){
$qty = $cart_item['quantity'];
break; // stop the loop if product is found
}
}
// Displaying the quantity if targeted product is in cart
if( ! empty( $qty ) )
echo '<p>Quantity for Product ID ' . $targeted_id . ' is: ' . $qty . '</p>;