woocommerce - programmatically update cart item qu

2019-03-30 02:15发布

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.

1条回答
Anthone
2楼-- · 2019-03-30 02:34

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:)

查看更多
登录 后发表回答