如何添加表现为缺货状态的WooCommerce自定义商品库存状态
解决WooCommerce自定义库存状态的不可购买行为调整
1. 标记自定义状态为“非可购买”状态
将以下代码添加到主题的functions.php文件或自定义插件中,让WooCommerce把你的两个自定义库存状态识别为类似“缺货”的不可购买状态:
// 标记自定义库存状态为非可用库存 add_filter('woocommerce_product_is_in_stock', 'custom_stock_status_in_stock', 10, 2); function custom_stock_status_in_stock($is_in_stock, $product) { $stock_status = $product->get_stock_status(); // 替换为你实际添加自定义状态时用的键名(比如你之前设置的'available_soon'和'in_store_only') if (in_array($stock_status, ['available_soon', 'in_store_only'])) { $is_in_stock = false; } return $is_in_stock; } // 设置自定义状态商品不可购买 add_filter('woocommerce_product_purchaseable', 'custom_stock_status_purchaseable', 10, 2); function custom_stock_status_purchaseable($is_purchaseable, $product) { $stock_status = $product->get_stock_status(); if (in_array($stock_status, ['available_soon', 'in_store_only'])) { $is_purchaseable = false; } return $is_purchaseable; }
注意:必须保证代码中的状态键名和你之前添加自定义库存状态时使用的键完全一致,否则逻辑不会生效。
2. 自定义前端库存状态文本显示
如果需要在前端显示你设置的自定义状态文本(而非默认的“缺货”),添加以下代码:
// 替换默认库存状态文本为自定义内容 add_filter('woocommerce_get_stock_html', 'custom_stock_status_html', 10, 2); function custom_stock_status_html($html, $product) { $stock_status = $product->get_stock_status(); switch ($stock_status) { case 'available_soon': $html = '<p class="stock available-soon">' . __('Available soon', 'woocommerce') . '</p>'; break; case 'in_store_only': $html = '<p class="stock in-store-only">' . __('In-store only', 'woocommerce') . '</p>'; break; } return $html; }
你可以通过available-soon和in-store-only这两个CSS类,为不同状态设置差异化的样式。
3. 拦截异常添加购物车行为
为了防止用户通过修改URL等非常规方式将这些商品加入购物车,添加以下验证代码:
// 禁止自定义状态商品添加到购物车 add_filter('woocommerce_add_to_cart_validation', 'custom_stock_status_add_to_cart_validation', 10, 3); function custom_stock_status_add_to_cart_validation($passed, $product_id, $quantity) { $product = wc_get_product($product_id); $stock_status = $product->get_stock_status(); if (in_array($stock_status, ['available_soon', 'in_store_only'])) { wc_add_notice(__('This item is not available for online purchase.', 'woocommerce'), 'error'); $passed = false; } return $passed; }
注意事项
- 建议先在测试环境验证代码,避免影响线上店铺正常运营。
- 如果使用了高度自定义的主题,需检查主题的商品模板文件是否覆盖了WooCommerce默认逻辑,若前端显示异常,可能需要调整主题模板以兼容上述过滤器。
内容的提问来源于stack exchange,提问作者Duncan S
相关产品推荐
相关产品推荐

