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

WooCommerce:隐藏0价/无主图产品,产品小工具仍显示问题求助

WooCommerce产品小工具未过滤0价/无主图产品?

现有代码可在WooCommerce存档页面隐藏价格为0或无主图的产品:

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $query ) {
    $meta_query = $query->get( 'meta_query' );

    $meta_query[] = array(
        'relation' => 'AND',
        array(
            'key' => '_thumbnail_id',
            'value' => '0',
            'compare' => '>',
        ),
        array(
            'key' => '_price',
            'value' => '0',
            'compare' => '>',
            'type' => 'NUMERIC',
        ),
    );

    $query->set( 'meta_query', $meta_query );
}

但在首页添加「Products」小工具时,仍会显示这类不符合条件的产品,请问遗漏了什么?


问题原因

woocommerce_product_query钩子仅作用于WooCommerce的主产品查询场景(如产品存档页、分类页、标签页等),而首页的Products小工具使用独立的小工具查询流程,不会触发这个钩子,所以过滤规则没生效。

修复代码

将过滤逻辑同时挂载到专门针对产品小工具的woocommerce_product_widget_query钩子上,复用同一个处理函数即可:

// 处理存档页等主产品查询
add_action( 'woocommerce_product_query', 'custom_filter_products' );
// 处理Products小工具查询
add_action( 'woocommerce_product_widget_query', 'custom_filter_products' );

function custom_filter_products( $query ) {
    // 给meta_query设置默认空数组,避免原查询无该参数时出错
    $meta_query = $query->get( 'meta_query', array() );

    $meta_query[] = array(
        'relation' => 'AND',
        array(
            'key' => '_thumbnail_id',
            'value' => '0',
            'compare' => '>',
        ),
        array(
            'key' => '_price',
            'value' => '0',
            'compare' => '>',
            'type' => 'NUMERIC',
        ),
    );

    $query->set( 'meta_query', $meta_query );
}

额外说明

  • 复用函数减少代码冗余,同时覆盖两种查询场景
  • 添加array()作为get('meta_query')的默认值,避免原查询未设置meta_query时出现数组拼接错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:32:03