如何计算ACF转发器输出中的总行数

Rob*_*ert 7 php mysql wordpress repeater advanced-custom-fields

问题:如何简单计算ACF转发器字段输出中的行?

目标:当只有一行而不是一行时,使输出看起来与css类不同.

我的代码:

if( have_rows('testimonials')) {
    $counter = 0;
    $numtestimonials = '';

    //loop thru the rows
    while ( have_rows('testimonials') ){
        the_row();
        $counter++;
            if ($counter < 2) {                         
                $numtestimonials = 'onlyone';               
            }
        echo '<div class="testimonial ' . $numtestimonials . '">';
           // bunch of output here
        echo '</div>';                          
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,我在这里这样做的方式不会起作用,因为第一次通过行时计数<2,所以即使计算了更多的行,它也会返回true.

谢谢!

Rob*_*ert 22

好的,我终于找到了答案.

计算ACF中继器中总行数的方法是:

$numrows = count( get_sub_field( 'field_name' ) );
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.如果转发器不是子字段(典型情况)那么它只是`count(get_field('field_name'));`. (4认同)
  • 这仍然对我不起作用。我在灵活的内容布局中有一个中继器。`have_rows`/`the_row` while 循环可以很好地打印转发器的内容,但是在转发器名称上调用的`get_sub_field` 或`get_field` 都不返回任何内容。如果我 `error_log` 输出 `get_sub_field` 或 `get_field` 的输出,我可以看到两者都没有返回,这就是我无法获得计数的原因。我的临时修复只是在主要循环之前重复 `have_rows`/`the_row` while 循环,只是为了计算 Repeater 中的所有行:/ 我讨厌这个解决方案。 (4认同)
  • 我有 5 个子字段,但我得到了 24 个,所以这似乎不再起作用。 (2认同)

Oti*_*eru 6

这对我有用, count 必须放在 if(have_rows('repeater_field') 之前:

三元运算符以避免中继器为空时出现警告错误

如果将计数放在“if(have_rows('repeater_field')) :”之后,则 count 返回 FALSE

$repeater_field = get_sub_field('repeater_field');
// OR if repeater isn't a sub_field
// $repeater_field = get_field('repeater_field');

// ternary operator to avoid warning errors if no result
$count =  $repeater_field ? count($repeater_field) : FALSE;

if(have_rows('repeater_field')) : // OR if($count) :

    echo 'Number of posts:' . $count . '<br>';

    while(have_rows('repeater_field')) : the_row();
        echo get_sub_field('field_name') . '<br>';
    endwhile;
endif;
Run Code Online (Sandbox Code Playgroud)