How to get a certain amount of product on a cart page in woocommerce

With this code:

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

I can get the amount of all products added to the cart, but I need this for a specific product.

+4
source share
3 answers

You should try the following:

// 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>;
+3
source
global $woocommerce;
    $items = $woocommerce->cart->get_cart();

    foreach($items as $item => $values) { 
        $_product = $values['data']->post; 
        echo "<b>".$_product->post_title.'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
        $price = get_post_meta($values['product_id'] , '_price', true);
        echo "  Price: ".$price."<br>";
    } 
+1
source

:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product = $values['data']->post; 
            echo "<b>".$_product->post_title.'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>
0

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


All Articles