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

全局开启缺货隐藏时,Woocommerce Products短码如何显示全量产品

WooCommerce 特定产品短码强制显示所有指定ID商品的解决方案

问题核心

全局开启「从目录中隐藏缺货商品」时,默认的[products]短码会继承这个过滤规则,导致缺货产品、以及父产品缺货但存在有库存变体的可变产品无法显示。要实现仅针对特定短码绕过该规则,可通过以下步骤解决:

1. 修改短码调用

在目标短码中添加自定义参数show_all="true",标记需要强制显示所有指定ID的商品:

[products ids="123,322,555,645,888" show_all="true"]

2. 添加过滤代码

将以下代码添加到子主题的functions.php文件或自定义功能插件中(避免直接修改主题核心文件,防止更新丢失):

add_filter( 'woocommerce_shortcode_products_query', 'force_show_all_targeted_products', 999, 3 );
function force_show_all_targeted_products( $query_args, $atts, $loop_name ) {
    // 仅处理带有show_all="true"参数的products短码
    if ( isset( $atts['show_all'] ) && $atts['show_all'] === 'true' ) {
        // 移除默认的库存状态过滤条件
        if ( isset( $query_args['meta_query'] ) ) {
            foreach ( $query_args['meta_query'] as $key => $query ) {
                if ( isset( $query['key'] ) && $query['key'] === '_stock_status' ) {
                    unset( $query_args['meta_query'][$key] );
                }
            }
            // 清理空的查询组
            $query_args['meta_query'] = array_filter( $query_args['meta_query'] );
            if ( empty( $query_args['meta_query'] ) ) {
                unset( $query_args['meta_query'] );
            }
        }

        // 强制包含有库存变体的可变产品
        $target_ids = $query_args['post__in'];
        $in_stock_variation_parents = get_posts( array(
            'post_type'      => 'product_variation',
            'post_parent__in'=> $target_ids,
            'meta_key'       => '_stock_status',
            'meta_value'     => 'instock',
            'fields'         => 'post_parent',
            'numberposts'    => -1,
            'post_status'    => 'publish'
        ) );

        // 合并原有ID和有库存变体的父产品ID,去重
        if ( ! empty( $in_stock_variation_parents ) ) {
            $query_args['post__in'] = array_unique( array_merge( $target_ids, $in_stock_variation_parents ) );
        }
    }

    return $query_args;
}

代码说明

  • 优先级设为999,确保覆盖WooCommerce默认的过滤逻辑
  • 仅对带有show_all="true"的短码生效,不影响全局或其他短码的库存隐藏规则
  • 移除默认的_stock_status过滤,让所有指定ID的产品都能被查询到
  • 额外查询并添加存在有库存变体的可变产品父ID,确保这类产品也能正常显示

内容的提问来源于stack exchange,提问作者Eduard Bakeš

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:05:17