我想知道如何根据为给定帖子查询的自定义帖子数量创建一组动态 ID。
我正在使用高级自定义字段插件,然后查询给定帖子中的自定义字段。如果您看一下下面的内容,您将看到我正在查询我的自定义字段,每个字段都包装在一个 id 为"section-1"的div 中。我需要的是每次查询新字段名称时,"部分-1"更新为"部分-3","部分-4"。因此,如果查询 5 个字段,则每个字段都有自己的 ID。
<?php
// check if the repeater field has rows of data
if( have_rows('repeater_field_name') ):
// loop through the rows of data
while ( have_rows('repeater_field_name') ) : the_row();
// display a sub field value
<div id="section-1">
the_sub_field('sub_field_name');
</div>
endwhile;
else :
// no rows found
endif;
?>
只需在循环之前设置一个 index
变量,并在每次迭代时递增它。在您的id
内使用它。
<?php
$index = 1;
while ( have_rows('repeater_field_name') ) : the_row(); ?>
<div id="section-<?= $index; ?>">
<?php the_sub_field('sub_field_name'); ?>
</div>
<?php $index++
endwhile; ?>
试试这个
<?php
// check if the repeater field has rows of data
if( have_rows('repeater_field_name') ):
$i = 0;
// loop through the rows of data
while ( have_rows('repeater_field_name') ) : the_row();
// display a sub field value
<div id="section-<?php echo ++$i; ?>">
the_sub_field('sub_field_name');
</div>
endwhile;
else :
// no rows found
endif;
?>