D
D
Denis_81062021-11-19 12:24:30
WordPress
Denis_8106, 2021-11-19 12:24:30

How to display a list using a loop in php (WP + ACF)?

Introductory: WP + ACF. I have a list like this in php.

<ul>
 <li><?php the_field('item1') ?></li>
 <li><?php the_field('item2') ?></li>
 <li><?php the_field('item3') ?></li>
 <li><?php the_field('item4') ?></li>
 ...
 <li><?php the_field('item15') ?></li>
</ul>


How can this list be output through a loop? (only number changes)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis_8106, 2021-11-19
@Denis_8106

There is a solution:

<ul>
       <?php for($i = 1; $i <= 15; $i++) : ?>
        <?php if( get_field(item' . $i) ): ?>
            <li><?php the_field(item' . $i) ?></li>
        <?php endif; ?>
        <?php endfor; ?>
 </ul>

A
Artem Zolin, 2021-11-19
@artzolin

$array = array();
$i = 1;

// собираем занчения в массив
while ( $i <= 15 ) {
  if ( $field = get_field( 'item' . $i ) ) {
    $array[] = $field;
  }
  $i++;
}

// выводим, если массив не пустой
if ( !empty( $array ) ) {
  echo '<ul>';
    foreach ( $array as $key => $value ) {
      echo '<li>' . $value . '</li>';
    }
  echo '</ul>';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question