gpt4 book ai didi

wordpress - Woocommerce 通过延期交货防止负变化库存

转载 作者:行者123 更新时间:2023-12-05 03:42:58 25 4
gpt4 key购买 nike

我的商店允许延期交货,但我不希望库存数量为负数。

我试着用这个来解决这个问题:

add_action('woocommerce_variation_set_stock', 'avoid_negative_stock', 10, 1);
function avoid_negative_stock( $product ) {
if ( did_action( 'woocommerce_variation_set_stock' ) >= 2 )
return;
if($product->get_stock_quantity() < 0){
$product->set_stock_quantity(0);
$product->save();
}
}

但它不起作用:/

谁能帮我解决这个问题?

问候

最佳答案

您可以使用 woocommerce_update_product_stock_query Hook 。
this answer您可以找到解决方案。

Keep in mind that it's not a good idea to force product inventorymanagement.

我举个例子:

  1. 您已为库存为 1 数量 的产品启用延期交货。
  2. 一位客户通过购买3 件 为该产品下了订单。
  3. 根据您的规则,产品的库存数量将为零 (而不是 -2)
  4. 订单被取消或退款,产品库存数量重置为 3 (而不是 1)

这是乘以同一产品的所有订单,这些订单因任何原因被取消和/或退款。 产品库存数量将不再可靠。

只要注意它。

也就是说,您可以像这样禁用负库存:

// disables the negative product stock quantity
add_filter( 'woocommerce_update_product_stock_query', 'disable_negative_stock_quantity', 10, 4 );
function disable_negative_stock_quantity( $sql, $product_id_with_stock, $new_stock, $operation ) {

global $wpdb;

// if the new stock quantity is negative, it sets zero
if ( $new_stock < 1 ) {
$new_stock = 0;
}

// generates SQL with the stock quantity at zero
$sql = $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = %f WHERE post_id = %d AND meta_key='_stock'", wc_stock_amount( $new_stock ), $product_id_with_stock );

return $sql;

}

代码已经过测试并且可以工作。将它添加到您的事件主题的 functions.php。

关于wordpress - Woocommerce 通过延期交货防止负变化库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67050390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com