have_rows()
Esta função verifica se o campo (repetidor ou conteúdo flexível) tem quaisquer linhas de dados para executar um loop. Esta é uma função booleana, ou seja, ele retorna VERDADEIRO ou FALSO.
Esta função é uma substituição para a função has_sub_field, no entanto, tem algumas diferenças pequenas mas significativas. A principal diferença é que esta função não percorre as linhas por si só, por isso, para percorrer as linhas, você também deve usar a função the_row.
Utilizar have_rows e the_rows juntos segue a mesma lógica de usar have_posts e the_post no Loop padrão do WP.
Parâmetros
<?php have_rows($field_name, $post_id); ?>
- $field_name: nome do campo repetidor / conteúdo flexível (obrigatório)
- $post_id: Especifica o ID do post onde o seu valor foi digitado. O padrão é pegar o do post atual, do loop que você está. Você também pode passar ID de uma página de opções, taxonomias, usuários, etc. (opcional)
Como utilizar
Loop Básico
<?php
if( have_rows('parent_field') ):
while ( have_rows('parent_field') ) : the_row();
// Your loop code
the_sub_field('sub_field');
endwhile;
else :
// no rows found
endif;
?>
Loop para um Campo Repetidor
<?php
if( have_rows('repeater') ): ?>
<ul class="slides">
<?php while( have_rows('repeater') ): the_row();
$image = get_sub_field('image');
?>
<li class="slide">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
<p class="caption"><?php the_sub_field('caption'); ?></p>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Loop para um campo de conteúdo flexível
<?php if( have_rows('flexible_content') ): ?>
<ul class="slides">
<?php while( have_rows('flexible_content') ): the_row(); ?>
<li class="slide">
<?php if( get_row_layout() == 'image_slide' ):
$image = get_sub_field('image'); ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
<?php elseif(get_row_layout() == 'video_slide' ):
the_sub_field('iframe');
endif; ?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Loop Aninhados
Este exemplo mostra um campo repetidor (locations) que contém um título, descrição e um outro campo repetidor dentro dele (staff_members) contendo membros da equipe.
A have_rows function irá detectar a troca de $field_name e iniciar um novo loop instantâneamente!
<?php // test loop #1
if( have_rows('locations') ): ?>
<div class="locations">
<?php // loop #1
while( have_rows('locations') ): the_row(); ?>
<div class="location">
<h3><?php the_sub_field('title'); ?></h3>
<p><?php the_sub_field('description'); ?></p>
<?php // loop #2 (aninhado)
<?php if( have_rows('staff_members') ): ?>
<ul class="staff-members">
<?php while( have_rows('staff_members') ): the_row();
$image = get_sub_field('image'); ?>
<li>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
<h4><?php the_sub_field('name'); ?></h4>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>



