Change the cart item quantity for specific products in woocommerce
17,776
To change quantities, see after that code. Here your revisited code:
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data']; // Get an instance of the WC_Product object
echo "<b>".$product->get_title().'</b> <br> Quantity: '.$cart_item['quantity'].'<br>';
echo " Price: ".$product->get_price()."<br>";
}
Updated: Now to change the quantity on specific products, you will need to use this custom function hooked in woocommerce_before_calculate_totals
action hook:
add_action('woocommerce_before_calculate_totals', 'change_cart_item_quantities', 20, 1 );
function change_cart_item_quantities ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE below define your specific products IDs
$specific_ids = array(37, 51);
$new_qty = 1; // New quantity
// Checking cart items
foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['data']->get_id();
// Check for specific product IDs and change quantity
if( in_array( $product_id, $specific_ids ) && $cart_item['quantity'] != $new_qty ){
$cart->set_quantity( $cart_item_key, $new_qty ); // Change quantity
}
}
}
Code goes in function.php file of the active child theme (or active theme).
Tested and works
Author by
lalaland
Updated on July 22, 2022Comments
-
lalaland over 1 year
Can I change WooCommerce quantity in some specific product?
I have tried:
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>"; }
How to get specific product Id in cart?
-
Anil Sharma over 3 yearsFor me the quantity is updating but the price is gone I am using this for the composite group products. Can you help me on this
-
LoicTheAztec over 3 years@AnilSharma As Composite products as part of a a third party plugin, this code doesn't handle this custom product type. You need to adapt it to your needs.
-
Anil Sharma over 3 yearsCan you guide me to achieve this.
-
LoicTheAztec over 3 years@AnilSharma Maybe ask a new question in StackOverFlow for Composite products…