Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

woocommerce - programmatically update cart item quantity

I am trying to programmatically update the quantity of a specific product in the cart if certain criteria is met.

I can easily update the price of the cart items with the following:

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 doesn't work but not quite sure how or if I can edit the quantity?

I also tried a these combinations that I found while digging around WooCommerce:

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

Again none of these worked.

like image 229
danyo Avatar asked Jun 04 '14 14:06

danyo


People also ask

How add item to cart programmatically WordPress?

You can add the product to the cart by calling the function WC()->cart->add_to_cart(); but you need to configure the cart_item_data in the below hook with the extra product option data. $cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id, $quantity );

How to add product in cart Programmatically in WooCommerce?

In order to add to the cart, we use the WC() class and the add_to_cart function inside cart. We will first need to empty the cart to ensure the product is not added multiple times if for example the user refreshes the page, also we can then optionally redirect the user to the cart page.

How do I get a cart quantity in WooCommerce?

WC()->cart->get_cart_contents_count() – it allows to get a number of cart items including their quantity counts. For example, if you have 10 snowboards and 1 avocado toast in the cart, this method will return 11 ! You can see it yourself if you open this method in WooCommerce source code.


1 Answers

To update the quantity:

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

How to get the $cart_item_key example:

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

And another example with a known cart_item_key:

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

Hope this helps:)

like image 180
shish Avatar answered Oct 13 '22 12:10

shish