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

如何用WooCommerce Products Bundles循环显示关联当前商品的捆绑包

解决WooCommerce显示当前商品关联捆绑包的问题

问题核心

当前代码仅筛选出所有类型为bundle的商品,但未关联当前商品——我们需要找出所有包含当前商品作为子商品的捆绑包。

解决方案(基于WooCommerce Product Bundles官方插件)

WooCommerce官方Product Bundles插件会将捆绑包包含的子商品ID存储在_wc_pb_bundled_items这个序列化元字段中。我们需要通过meta_query匹配包含当前商品ID的捆绑包,同时保留原有的tax_query筛选bundle类型商品。

修改后的完整代码:

<?php
global $post;
// 仅在商品页面执行逻辑
if ( ! is_product() ) return;

$current_product_id = $post->ID;

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 99,
    'orderby'        => 'date',
    'post_status'    => 'publish', // 只显示已发布的捆绑包
    'tax_query'      => array(
        array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => 'bundle',
        ),
    ),
    'meta_query'     => array(
        array(
            'key'     => '_wc_pb_bundled_items',
            'value'   => '"product_id";i:' . $current_product_id . ';',
            'compare' => 'LIKE',
        ),
    ),
);

$query = new WP_Query($args);

if ($query->have_posts()): 
    while ($query->have_posts()): $query->the_post();
        $title = get_the_title(get_the_ID()); ?>
        <div><?php echo esc_html($title); ?></div>
    <?php endwhile;
    wp_reset_postdata(); // 恢复全局post对象,避免后续代码异常
else: ?>
    <div class="col-12 text-center">
        <h4 class="title">目前没有与该商品关联的捆绑包。</h4>
    </div>
<?php endif; ?>

关键修改说明

  • 新增meta_query:通过匹配_wc_pb_bundled_items元字段中的当前商品ID,精准筛选包含它的捆绑包(序列化数组格式固定,所以用特定字符串匹配)。
  • 添加post_status限制:确保只查询已发布的商品,排除草稿、未上架的捆绑包。
  • 增加wp_reset_postdata():自定义WP_Query会修改全局post对象,执行后必须恢复,防止后续模板调用出错。
  • 用esc_html()处理标题输出:符合WordPress安全规范,避免XSS风险。

适配第三方捆绑包插件的注意事项

如果你的捆绑包是第三方插件实现的,需要调整meta_query中的键名。可以通过查看数据库wp_postmeta表,找到存储捆绑包子商品的元键,替换代码中的_wc_pb_bundled_items即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:36:01