WooCommerce产品缺货时移除归档页、商品及分类页数量选择框
如何在WooCommerce缺货时移除数量选择框?
没问题!要实现缺货时从商店页、分类页(归档页)和商品详情页移除数量选择框,我们可以在你现有代码的基础上做调整,再补充商品详情页的处理逻辑,两步就能搞定:
1. 修改归档页的数量框代码(商店/分类页)
你之前的代码是在归档页添加数量框,现在我们只需要新增库存判断条件,当产品缺货时就不渲染这个数量框:
/** * Add quantity field on archive pages ONLY if product is in stock. */ function custom_quantity_field_archive() { $product = wc_get_product( get_the_ID() ); // 核心判断:产品缺货时直接返回,不显示数量框 if ( ! $product->is_in_stock() ) { return; } // 保留你原有的逻辑:非单独销售、非可变产品才显示数量框 if ( ! $product->is_sold_individually() && 'variable' !== $product->get_type() ) { woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->get_max_purchase_quantity(), 'input_value' => 1, ) ); } } add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 11 );
这里我还把$product->product_type改成了$product->get_type()——这是WooCommerce官方推荐的写法,避免直接访问对象属性,兼容性更好。
2. 处理商品详情页的数量框
商品详情页默认会显示数量框,我们可以通过过滤器或者钩子来控制,这里推荐用过滤器修改数量框参数的方式,比直接移除钩子更稳妥(适配更多主题):
/** * Hide quantity field on single product page when product is out of stock. */ function custom_hide_single_product_quantity( $args, $product ) { // 产品缺货时,把数量框设为隐藏 if ( ! $product->is_in_stock() ) { $args['hidden'] = true; } return $args; } add_filter( 'woocommerce_get_quantity_input_args', 'custom_hide_single_product_quantity', 10, 2 );
如果你的主题用了自定义的数量框渲染逻辑,上面的方法没生效的话,可以试试直接移除数量框的钩子:
/** * Remove quantity field on single product page when out of stock. */ function custom_remove_single_quantity_field() { global $product; if ( ! $product->is_in_stock() ) { remove_action( 'woocommerce_before_add_to_cart_quantity', 'woocommerce_quantity_input', 10 ); } } add_action( 'woocommerce_before_add_to_cart_form', 'custom_remove_single_quantity_field' );
注意事项
- 把代码添加到你当前主题的
functions.php文件末尾,或者用Code Snippets这类自定义代码插件(更安全,避免主题更新丢失代码)。 - 如果是可变产品(Variable Product),每个变体的库存需要单独处理,这时候可能需要配合JavaScript监听变体切换事件来动态显示/隐藏数量框,如果你需要这部分逻辑可以再提出来~
内容的提问来源于stack exchange,提问作者James Donald
相关产品推荐
相关产品推荐

