使用分类字段 (ACF) 获取产品类别 (Woocommerce) 以过滤循环

Get product category (Woocommerce) with the taxonomy field (ACF) to filter the loop

目前,我正在一个网站上工作,我必须在其中显示 posts 以及在分类字段中选择的类别;我为此使用高级自定义字段。对于“正常”(单个)posts 和自定义 post 类型,它就像一个魅力。展示它是如何工作的:

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

    $catact = get_field('actueel_category', $term);

    $loop = new WP_Query( array(
        'post_type' => 'actueel',
        'posts_per_page' => 2,
        'category__in' => $catact,
      )
    );
    ?>
    <?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_query(); ?>

现在,当我尝试对 Woocommerce 产品执行相同操作时,它不起作用。这是我为此使用的代码:

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

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

    $loop = new WP_Query( array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        'product_cat' => $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_query(); ?>

有什么我没有得到的吗?

在管理区域:我使用分类法字段,两个输出都显示为术语 ID。对于常规 post,我选择了“类别”分类法,对于产品,我选择了“product_cat”分类法。

有人可以和我一起思考吗?我似乎无法解决它。也许我忽略了什么。

提前致谢!

您正在 WP_Query 中使用 product_cat 参数。不支持。

在产品循环参数中使用 category__in

$loop = new WP_Query( array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'category__in' => $catpro,
  )
);

正在使用

'product_cat' => $catpro,

在WP_Query中是错误的。这种使用分类法参数的方法仅适用于类别分类法——这是来自 WordPress 较旧版本的遗留支持。这就是为什么对于 WP_Query 中的非类别分类法,您需要使用 tax_query.

f.e.

 $loop = new WP_Query( array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        'tax_query' => array(
               array(
                 'taxonomy' => 'product_cat',
                 'field'    => 'term_id',
                 'terms'    => $catpro,
               ),
             ),
           )
         );

但不要忘记调整 FIELD 和 TERMS 值。因为我不知道你的 $catpro 变量是什么,所以我只写了代码作为例子。 字段可以有 term_id、slug、名称 值。

有关更多示例,请查看 https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters