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

如何通过ACF分类法字段获取Woocommerce商品分类过滤查询循环

问题根因

你代码失效的核心原因是WP_Query 中product_cat参数仅支持传入商品分类的别名(slug),但你的ACF分类法字段配置的输出格式是术语ID,参数值格式不匹配导致查询无法命中结果。
你之前普通文章查询正常,是因为使用了专门接收分类ID的category__in参数,和ACF返回的ID格式正好匹配。

修复方案

推荐使用通用的tax_query参数配置自定义分类法查询,兼容性更强,适配你当前返回ID的配置,修改后的查询代码如下:

<?php
// get the current taxonomy term
$term = get_queried_object();

$catpro = get_field('product_category', $term);

// 增加非空判断,避免字段为空时查询出全部商品
if ( $catpro ) :
    $loop = new WP_Query( array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        // 用tax_query明确指定按分类ID查询
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => $catpro,
            )
        )
    ) );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <a href="<?php the_permalink();?>">
        <div class="post">
            <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
            <div class="thumbnail" style="background-image:url('<?php echo $thumb['0'];?>');">
            </div>
            <div class="theme__inner__content">
                <h4><?php the_title();?></h4>
                <span class="more">lees meer</span>
            </div>
        </div>
    </a>
<?php endwhile; 
// 自定义查询推荐用wp_reset_postdata()重置,比wp_reset_query()更适配场景
wp_reset_postdata(); 
endif;
?>

额外说明

如果你不想改查询结构,也可以将ACF字段的输出格式修改为「术语别名」,原有'product_cat' => $catpro的写法也能正常运行,但用tax_query的方式扩展性更强,后续如果要加多个分类筛选、层级筛选等需求都能直接扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:18:03