I am using 2 if else statements where the first set just displays 4 results, and the second should display all results (including the initial 4)
I have got the counter working but it also effects the second set of results (which only displays the remaining results minus the first 4) and I can’t work out how to unset the variable.
I have tried using ‘unset’ in different places, also tried setting a new rule for the second batch but nothing works. Unset works at different places but also unsets the initial 4, thereby displaying all on both.
Any help would be greatly appreciated
<section>
<div class="full-width-inner">
<div class="find-anything-mobile-grid">
<?php if ( have_rows( 'carousel_search_item' ) ) : ?>
<?php $i = 0; ?>
<?php while ( have_rows( 'carousel_search_item' ) ) : the_row(); ?>
<?php $i++; ?>
<?php if( $i > 4 ): ?>
<?php break; ?>
<?php endif; ?>
<div class="lenses-carousel-slide">
<p>content</p>
</div>
<?php unset($i); ?>
<?php endwhile; ?>
<?php else : ?>
<?php // No rows found ?>
<?php endif; ?>
</div>
<div class="find-anything-mobile-grid-popup">
<?php if ( have_rows( 'carousel_search_item' ) ) : ?>
<?php while ( have_rows( 'carousel_search_item' ) ) : the_row(); ?>
<div class="lenses-carousel-popup-item">
<p>content</p>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php // No rows found ?>
<?php endif; ?>
</div>
</div>
</section>
2
Answers
$i
has no effect on the rows that are printed withthe_row()
.To go back to the first row, use the undocumented function
reset_rows('carousel_search_item')
between the two loops.This is mostly comment, but space there is limited.
Your code is virtually unreadable. Please go and have a look at some PHP style guides. If your code contains
?>[whitespace]<?php
then its wrong. Removing that is slightly better but its still confused. Why do you have empty ‘else’ blocks?Cleaning this up, makes some of the bugs more obvious (to me at least):
(but stackoverflow’s syntax highlighter can’t make sense of this)
We don’t know what "have_rows()" and "the_row()" are doing – but it smells like they are operating on the same data which is not being passed as a parameter. That’s BAD.
You have 2 exits from your loop defined in different places. That;s BAD.
You are using $i as way of limiting the loop – but unsetting this variable in the middle of the loop. That’s BAD.
Unless you are doing something really, REALLY bad with scope then you’ve got malleable state inside "the_row()" – which is also BAD.
Move your data pointer outside of your functions.
Given the description of what you are trying to achieve, I would have written something like: