Reputation: 563
I'm looking for a nice solution to always show a set number of elements - in this case 3 - even if the while loop test expression is false.
This is to get a uniform grid layout, so that I don't need to mess around with equal height columns etc...
CODE
<ul class="event__lineup">
<?php
$l = 0;
while ( has_sub_field('event_lineup') ) :
echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';
if ( $l == 2 ) : break; endif;
$l++;
endwhile;
?>
</ul>
I'm looking to use a placeholder if say there's only 1 artist or 2:
echo '<li class="title"> </li>';
I understand a while loop maybe isn't the best solution, however, I'm not sure how to approach a different solution.
EDIT
<ul class="event__lineup">
<?php
for ($i = 0; $i < 3; $i++) {
if ( has_sub_field('event_lineup') ) {
echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';
} else {
echo '<li class="title"> </li>';
}
}
?>
</ul>
Upvotes: 2
Views: 134
Reputation: 120714
<ul class="event__lineup">
<?php
$done = false;
for ($i = 0; $i < 3; $i++) {
if (!has_sub_field('event_lineup')) {
$done = true;
}
if ($done) {
echo '<li class="title"> </li>';
} else {
echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';
}
}
?>
</ul>
The for
loop will execute 3 times regardless of the results of the call to has_sub_field
. It appears - based on the results you were getting in your initial testing - that once has_sub_field
returns false
, the next call to has_sub_field
will reset its internal index and it will start over from the beginning.
So we set $done
to true
the first time that has_sub_field
returns false
and then use $done
to decide when we print the sub field and when we print the placeholder <li>
.
Upvotes: 3
Reputation: 683
Placing this after your Loop should check how many elements are missing to reach the minimum number to show and echo the correct number of placeholders:
$minimumNumberToShow = 3;
if($l < 3){
for($i; $ < ($minimumNumberToShow-$l);; $i++){
echo '<li class="title"> </li>';
}
}
Upvotes: 0