9
9
999kseni9992019-12-03 10:38:08
WordPress
999kseni999, 2019-12-03 10:38:08

Word Press: How to reduce the balance when adding to cart in woocommerce?

Hello,
There was a need to reduce the balance "in stock" at the time of adding the product to the cart.
That is, the user added 2 things to the cart, and, accordingly, the balance decreased by 2, without updates, immediately after clicking on the cart. And this decrease is immediately visible to everyone who is online
Please help me how to do this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
9
999kseni999, 2019-12-03
@999kseni999

Might be useful to someone:

add_action('woocommerce_add_to_cart', 'update_product_stock_on_add', 10, 6);

function update_product_stock_on_add($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
    global $woocommerce;

    $product = get_product($product_id);

    $woocommerce->cart->cart_contents[$cart_item_key]['old_stock_quantity'] = $product->get_stock_quantity();
    $woocommerce->cart->cart_contents[$cart_item_key]['add_time'] = time();

    wc_update_product_stock($product_id, $product->get_stock_quantity() - $quantity);
}

add_action('woocommerce_after_cart_item_quantity_update', 'update_product_stock_on_update', 10, 2);

function update_product_stock_on_update($cart_item_key, $quantity) {
    global $woocommerce;

    $cart_item = $woocommerce->cart->cart_contents[$cart_item_key];

    wc_update_product_stock($cart_item['product_id'], $cart_item['old_stock_quantity'] - $quantity);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question