提问者:小点点

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


目前,我正在一个网站上工作,在那里我必须用分类法字段选择的类别显示帖子;我为此使用高级自定义字段。使用“普通”(单一)帖子和自定义帖子类型,它就像一个符咒。要显示其工作原理,请执行以下操作:

<?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。对于常规帖子,我选择了“类别”分类法,对于产品,选择了“产品类别”分类法。

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

提前谢谢!


共2个答案

匿名用户

使用

'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,段,名称值。

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

匿名用户

您正在WP\U查询中使用product\u cat参数。这是不受支持的。

在产品循环参数中使用category__in

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