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 必须放在 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)
| 归档时间: |
|
| 查看次数: |
17071 次 |
| 最近记录: |