在 WP_Query 中间重置计数

Reset count in middle of WP_Query

我有一个 WP_Query 查询 CPT 'projects' 以获取作者详细信息。从 ACF 转发器字段获取作者时,如果有多个作者,我想在他们之间添加单词 'and'。

这个在单个项目上工作得很好,但是当我查询所有项目时,子循环后计数不会重置。不确定是否需要重置计数 and/or 如果我需要计算转发器中的项目数量,如果大于 2 那么 运行 代码?

不管怎样,不知道该怎么做,希望有人能给我一些指示。

<?php
  $args = array(
 'post_type' => 'showcase',
 'posts_per_page' => -1,
 'orderby' => 'rand',
);
$projects = new WP_Query($args);
?>
<?php if($projects->have_posts()) : ?>
<?php while($projects->have_posts()) : $projects->the_post() ?>
  // some content here
        <?php $i==1; while( have_rows('project_author') ): the_row(); ?>
        <?php if($i ==1)
        {
        echo "and";
        }; ?>
        <?php the_sub_field('screenwriters_name'); ?>
        <?php $i++; endwhile; ?>
<?php  endwhile ?>
<?php endif ?>
<?php wp_reset_postdata(); ?>

感谢

您在尝试将 $i 设置为 1 时使用了相等运算符。您需要改用赋值运算符(单等号而不是双等号)。

目前 $i 仅在您 运行 $i++ 之后变为 1,这将导致一些意外行为。如果在代码顶部将 $i 正确设置为 1,则 while 循环中用于输出 'and' 的 if 语句将在循环的第一次迭代中 运行。

我在使用的逻辑中看到的另一个问题是 'and' 将只输出一次,无论转发器字段中有多少作者。

有几种方法可以解决这个问题。

解决方案 1 - 修复错误

<?php while ( $projects->have_posts() ) : $projects->the_post(); ?>

    <?php $i = 1; // fix assignment

    while( have_rows( 'project_author' ) ): the_row();

        // run on all iterations of the loop except the first.
        if ( $i > 1 ) {
            echo ' and '; // add space before and after string.
        }

        the_sub_field( 'screenwriters_name' );

        $i++;
    endwhile; ?>
<?php endwhile; ?>

解决方案 2 - 将字段视为数组并使用 implode()

我觉得这个解决方案更干净。我们将检索作者字段作为数组,而不是使用转发器函数 (have_rows() / the_row()) 循环遍历。

<?php while ( $projects->have_posts() ) : $projects->the_post(); ?>

    <?php $project_author = get_field( 'project_author' );

    if ( $project_author ) {

        // extract screenwriters_name values (the sub field name) from the fields array.
        $screenwriter_names = array_column( $project_author, 'screenwriters_name' );

        // join elements of the array into a string. ' and ' is only used when more than one.
        echo implode( ' and ', $screeenwriter_names );
    }  ?>
<?php endwhile; ?>