You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中排除所有关联产品目录隐藏的pa_brand术语

过滤WooCommerce品牌属性术语:排除所有关联产品均隐藏的术语

原代码里的hide_empty => true只能排除完全没有关联产品的品牌术语,但如果某个品牌下的所有产品都把目录可见性设为hidden,这个品牌还是会被列出来。要解决这个问题,我们可以在获取术语后,额外校验每个品牌下是否存在至少一个可见产品,具体修改如下:

add_shortcode( 'product_attributes', 'get_product_attributes' );

function get_product_attributes() {
    $attribute_name = 'pa_brand';
    
    // 先获取所有非空的品牌术语
    $terms = get_terms([
        'taxonomy' => $attribute_name,
        'hide_empty' => true,
    ]);
    
    if ( ! is_wp_error( $terms )){
        $html = '<ul>';
        
        foreach ( $terms as $term ) {
            // 查询当前品牌下,状态为发布且目录可见性不是hidden的产品
            $visible_products = wc_get_products([
                'status' => 'publish',
                'tax_query' => [
                    [
                        'taxonomy' => $attribute_name,
                        'field'    => 'term_id',
                        'terms'    => $term->term_id,
                    ],
                ],
                'meta_query' => [
                    [
                        'key'     => '_visibility',
                        'value'   => 'hidden',
                        'compare' => '!=',
                    ],
                ],
                'return' => 'ids',
                'limit'  => 1, // 只要查到1个就够,不用查全部,提升效率
            ]);
            
            // 只有存在可见产品时,才输出这个品牌的链接
            if ( ! empty( $visible_products ) ) {
                $link = get_term_link( $term->slug, $attribute_name );
                $html .= '<li><a href="' . esc_url( $link ) . '">' . esc_html( $term->name ) . '</a></li>';
            }
        }
        
        $html .= '</ul>';
        return $html;
    }
}

关键改动说明:

  • 新增wc_get_products查询,针对每个品牌术语筛选发布状态且目录可见性不为hidden的产品
  • 设置limit => 1减少查询压力,只要存在至少1个可见产品就满足输出条件
  • 用esc_url和esc_html对链接、术语名称做转义,避免XSS风险
  • 只有通过校验的品牌术语才会被加入输出列表

内容的提问来源于stack exchange,提问作者SierraEcho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 11:55:18