如何仅为ID=29的分类应用WooCommerce变量商品最高价格显示代码
WooCommerce 指定分类下变量商品仅显示最高售价实现方案
修改后的完整可直接使用代码如下:
// 自定义变量商品价格显示规则,仅对ID为29的商品分类生效 function filter_woocommerce_variable_price_html( $wc_format_price_range, $instance ) { // 判断当前商品是否属于指定分类,不属于则直接返回原价格格式 if ( ! has_term( 29, 'product_cat', $instance->get_id() ) ) { return $wc_format_price_range; } $index = strpos($wc_format_price_range, "– "); // 兼容特殊场景:未找到价格分隔符时直接返回原内容,避免PHP报错 if ( $index === false ) { return $wc_format_price_range; } $wc_format_price_range = substr($wc_format_price_range, $index + 7); return "Max Price: " . $wc_format_price_range; }; // 挂载WooCommerce价格过滤钩子 add_filter( 'woocommerce_variable_price_html', 'filter_woocommerce_variable_price_html', 10, 2 );
调整说明
- 新增分类判断逻辑:调用WordPress内置
has_term函数校验商品所属分类,非指定分类下的商品完全沿用默认价格展示规则,不会做任何修改 - 新增异常兼容逻辑:避免部分特殊价格格式下找不到分隔符导致页面报错,不需要该判断可直接删除
- 优化了原代码的冗余写法,删除了多余的赋值操作和冗余分号
- 可选扩展:如果需要同时适配多个分类,可将
has_term第一个参数替换为分类ID数组,例如has_term( [29,31,35], 'product_cat', $instance->get_id() )即可同时对多个分类生效
内容的提问来源于stack exchange,提问作者abrecaminosdesign
相关产品推荐
相关产品推荐

