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

Woocommerce如何隐藏归档页缺货产品且排除带backorder标签的产品

Woocommerce归档页隐藏缺货产品(backorder标签产品除外)解决方案

原有代码问题

你当前分开添加meta_query和tax_query的写法,默认两个查询条件为AND逻辑,最终只会显示「同时满足有货、且带有backorder标签」的产品,和需求完全不符。

可行实现代码

add_action( 'woocommerce_product_query', 'custom_hide_outofstock_except_backorder', 10, 2 );
function custom_hide_outofstock_except_backorder( $q, $query ) {
    // 仅在前台非搜索的店铺页面生效,排除后台、搜索页
    if ( is_admin() || is_search() || ! is_shop() ) return;

    // 查询所有「缺货且不带backorder标签」的产品ID
    $exclude_ids = get_posts( [
        'post_type' => 'product',
        'posts_per_page' => -1,
        'fields' => 'ids',
        'meta_query' => [
            [
                'key' => '_stock_status',
                'value' => 'outofstock',
                'compare' => '=',
            ]
        ],
        'tax_query' => [
            [
                'taxonomy' => 'product_tag',
                'field' => 'name',
                'terms' => ['backorder'],
                'operator' => 'NOT IN',
            ]
        ]
    ] );

    // 将不符合规则的产品从主查询中排除
    if ( ! empty( $exclude_ids ) ) {
        $existing_exclude = $q->get( 'post__not_in' ) ?: [];
        $q->set( 'post__not_in', array_merge( $existing_exclude, $exclude_ids ) );
    }
}

注意事项

  • 若需要覆盖产品分类、产品标签等所有Woocommerce归档页面,可将判断条件中的! is_shop()修改为! ( is_shop() || is_product_category() || is_product_tag() )
  • 若你使用标签slug而非名称匹配,将'field' => 'name'修改为'field' => 'slug'即可
  • 站点产品数量超过1000的情况下,建议给$exclude_ids的查询结果添加transient缓存,设置24小时过期,避免每次页面加载都查询数据库,提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:12:01