减少产品库存添加到购物车 - Woocommerce

时间:2014-06-13 12:21:43

标签: php wordpress woocommerce cart stock

有一个(希望很快!)问题,当产品被添加到购物车时更新产品的库存水平(如果在结账前将它们从购物车中移除,最好“释放”它们) - 它是多么容易实现这样的目标,最好的步骤是什么?

我可以看到有一些函数/过滤器可以像woocommerce_stock_amount,wc_update_product_stock和add_to_cart_class等一样调用,但是我会喜欢你可以在如何将它们组合在一起的任何指导:)< / p>

到目前为止,这是已经达到的目标,并且它运作良好,但有一个相当重要的问题!如果产品是“一次性”,换句话说,只有一个产品在添加到购物车之前只有一个库存,访客无法结账,因为下面的脚本已将库存减少到零!

提前感谢您对此的任何帮助:)

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);
}

add_action('woocommerce_before_cart_item_quantity_zero', 'update_product_stock_on_zero', 10, 2);

function update_product_stock_on_zero($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']);
}

add_filter('woocommerce_get_cart_item_from_session', 'load_old_stock_from_session', 10, 3);

function load_old_stock_from_session($cart_item, $values, $key) {
    $cart_item['old_stock_quantity'] = $values['old_stock_quantity'];
    $cart_item['add_time'] = $values['add_time'];

    return $cart_item;
}

add_action('woocommerce_cart_loaded_from_session', 'check_cart_item_timeout');


function check_cart_item_timeout($cart) {
    foreach ($cart->get_cart() as $cart_item_key => $values) {
        if ((time() - $values['add_time']) >= 10) {

            wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $values['data']->get_title() ), 'error' );
            unset($cart->cart_contents[$cart_item_key]);
            wc_update_product_stock($values['product_id'], $values['old_stock_quantity']);

        }
    }

}

0 个答案:

没有答案