woocommerce - programmatically update the number of items in the basket

I am trying to programmatically update the quantity of a certain product in the basket if certain criteria are met.

I can easily update the price of the goods in the basket as follows:

add_action( 'woocommerce_before_calculate_totals', 'wwpa_simple_add_cart_price' );
function wwpa_simple_add_cart_price( $cart_object ) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
                $value['data']->price = '1';
}}

In the function above, I tried to add:

$value['data']->quantity= '10';

This does not work, but not quite sure how or if I can change the quantity?

I also tried these combinations, which I found while delving into WooCommerce:

$value['data']->quantity= '10';
$value['data']->qty= '10';
$value['quantity'] = '10';

Again, none of this worked.

+4
source share
1 answer

To update the quantity:

global $woocommerce;
$woocommerce->cart->set_quantity($cart_item_key, '100');

How to get an example of $ cart_item_key:

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
    echo $cart_item_key;
} 

And another example with the famous cart_item_key:

global $woocommerce;
$woocommerce->cart->set_quantity('8d317bdcf4aafcfc22149d77babee96d', '100');

Hope this helps :)

+10
source

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


All Articles