分类法(类别)中的 ACF 转发器不起作用

ACF repeater in taxonomy (category) doesn't work

在分类类别中我有:

中继器字段名为 问题。 在中继器内,我有一个名为 answer.

的字段

我试图在 category.php 文件中显示所有答案,如下所示:

$term = get_queried_object();

if ( have_rows( 'questions',   $term ) ) {
    while( have_rows( 'questions',   $term ) ) {
        the_row();
        the_sub_field( 'answer' );
    }
}

没用。你能告诉我这里有什么问题吗?我已经尝试了几个小时才能让它发挥作用。

您是否尝试过将您的字段作为数组循环?这通常更容易,尤其是当您获得的字段不属于全局 $post 的一部分时。相反,您的设置将如下所示:

$questions = get_field( 'questions', $term );
foreach( $questions as $question ){
    echo $question[ 'answer' ];
}

我发现这更容易。我猜你上面的问题与 the_row() 没有正确获取全局循环有关,因为你正在访问 $term 的字段,但我不确定。无论如何 - 上面的代码应该可以工作。

我终于明白了。我检查了存储数据的 phpmyadmin。原来数据是保存在wp_termmeta里的,并不是我想的在wp_postmeta里。这就是为什么大多数解决方案都不起作用的原因。

使用 get_term_meta 而不是 ACF 代码(循环和函数)将转发器添加到分类法(我的示例中的类别)的工作变通代码。

<?php
  // name of repeater field
  $repeater = 'questions'; 

  // get taxonomy id
  $taxonomy_id = get_queried_object_id(); 

  // get repeater data from term meta
  $post_meta = get_term_meta($taxonomy_id, $repeater, true);

  // count items in repeater
  $count = intval(get_term_meta($taxonomy_id, $repeater, true));

  // loop + apply filter the_content to preserve html formatting
  for ($i=0; $i<$count; $i++) {
      echo apply_filters('the_content', get_term_meta($taxonomy_id, $repeater.'_'.$i.'_'.'title', true));
      echo apply_filters('the_content', get_term_meta($taxonomy_id, $repeater.'_'.$i.'_'.'answer', true));
    }
  ?>

文档中的解决方案仍然不适用于分类法中的转发器。它确实适用于 non-repeaters(例如图像,添加到分类法的文本)。 https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

如果有人仍在寻找解决方案,请参考我的方法。

            <?php 
                $term = get_queried_object();
                $taxonomy = $term->taxonomy;
                $term_id = $term->term_id;  
                if( have_rows('highlight_boxes', $taxonomy . '_' . $term_id) ):
                while(have_rows('highlight_boxes', $taxonomy . '_' . $term_id)): 
                the_row(); 
            ?> 

                <div class="column">
                    <h2 class="heading-title"><?php the_sub_field('highlight_title', $taxonomy . '_' . $term_id) ?></h2>
                    <div class="description">
                        <p><?php the_sub_field('highlight_desc', $taxonomy . '_' . $term_id) ?></p>
                    </div>
                </div>
            
            <?php endwhile; endif; ?>