Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get particular product quantity from the cart page in the woocommerce

With this code:

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

I can get the quantity of all the products added in cart but I need it for the particular product.

like image 383
vivek raj Avatar asked Jun 19 '17 13:06

vivek raj


3 Answers

You can loop through cart items to get the quantity for a specific product id as follows:

// Set here your product ID (or variation ID)
$targeted_id = 24;

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) { 
    if( in_array( $targeted_id, array($cart_item['product_id'], $cart_item['variation_id']) )){
        $quantity =  $cart_item['quantity'];
        break; // stop the loop if product is found
    }
}
// Displaying the quantity if targeted product is in cart
if( isset( $quantity ) && $quantity > 0 ) {
    printf( "<p>" . __("Quantity for Product ID %d is: %d") . "</p>", $targeted_id, $quantity );
}

Or you can also use the WC_Cart method get_cart_item_quantities() as follow:

// Set here your product ID (or variation ID)
$targeted_id = 24;

// Get quantities for each item in cart (array of product id / quantity pairs)
$quantities = WC()->cart->get_cart_item_quantities(); 

// Displaying the quantity if targeted product is in cart
if( isset($quantities[$targeted_id]) && $quantities[$targeted_id] > 0 ) {
    printf( "<p>" . __("Quantity for Product ID %d is: %d") . "</p>", $targeted_id, $quantities[$targeted_id] );
}

Note: This last way doesn't allow to target the parent variable product.

like image 145
LoicTheAztec Avatar answered Nov 18 '22 20:11

LoicTheAztec


$cart = WC()->cart->get_cart();
$product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
if( WC()->cart->find_product_in_cart( $product_cart_id )) {
    echo($cart[$product_cart_id]['quantity']);
}
like image 32
Geza Gog Avatar answered Nov 18 '22 18:11

Geza Gog


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>";
    } 
like image 2
Pankaj Patel Avatar answered Nov 18 '22 19:11

Pankaj Patel