如何在WooCommerce可变产品页面隐藏缺货变体?
WooCommerce隐藏缺货产品变体的解决方案
你当前使用的woocommerce_variation_is_active过滤器仅会将缺货变体制为“非活跃”状态(表现为灰化按钮),但不会直接隐藏变体。要实现彻底隐藏缺货变体的需求,可以通过以下两种关键钩子组合实现:
1. 从可用变体列表中移除缺货变体
该过滤器会直接从产品的可用变体集合中删除缺货条目,确保这类变体不会被加载到页面中:
/** * 移除缺货的产品变体 */ add_filter( 'woocommerce_available_variations', 'remove_out_of_stock_variations', 10, 2 ); function remove_out_of_stock_variations( $variations, $product ) { // 过滤并保留仅有库存的变体 $variations = array_filter( $variations, function( $variation ) { return $variation['is_in_stock']; } ); return $variations; }
2. 隐藏属性下拉框中对应无库存的选项
如果需要连属性选择器(比如尺码、颜色下拉框)中的缺货选项也隐藏,添加以下代码:
/** * 隐藏属性下拉框中无对应库存的选项 */ add_filter( 'woocommerce_variation_option_name', 'hide_out_of_stock_variation_options', 10, 3 ); function hide_out_of_stock_variation_options( $option_name, $option, $product ) { $variations = $product->get_available_variations(); $has_matching_in_stock = false; // 遍历所有变体,检查当前属性选项是否存在有库存的对应变体 foreach ( $variations as $variation ) { foreach ( $variation['attributes'] as $attr_key => $attr_value ) { $attr_slug = str_replace( 'attribute_', '', $attr_key ); if ( $attr_slug === $option->get_name() && $attr_value === $option_name ) { if ( $variation['is_in_stock'] ) { $has_matching_in_stock = true; break 2; } } } } // 仅当存在对应有库存变体时,显示该选项 return $has_matching_in_stock ? $option_name : ''; }
使用说明
- 替换你现有的
grey_out_variations_when_out_of_stock相关代码,或者直接添加上述两个函数到主题的functions.php文件中。 - 测试前请清除WooCommerce缓存和浏览器缓存,确保新代码生效。
内容的提问来源于stack exchange,提问作者Enes Bajrami
相关产品推荐
相关产品推荐

