Counter problem, infinite loop when post_per_page equals X

(updated)

I´m using this query to loop divs in to my front page slider. I use counters to split 4 posts into a slider, then open a new slider etc. Also a counter to set a class to every fourth post (to fix margin). This worked great until I wanted to use the ‘post_per_page’ argument. If I put it to -1 or something dividable by 4, I get an infinite loop that loops in all posts ad infinitum.

Read More

So. It´s pretty clear that my problem has to do with the counters. I´m not a coder myself and put this code together from different sources and with the help of the almighty internet.

This is what my full query looks like:

<ul id="slider1">
<?php 
$args = array(
'post_type' => 'fastighet',
'posts_per_page' => -1,
'orderby' => 'ASC'
             );
?>
<?php $query = new WP_Query( $args ); ?> 
<?php if( $query->have_posts() ) : ?>
<li class="4slide">     
<?php $count = 0; ?>    
<?php while ($query->have_posts()) : $query->the_post(); $c++;
if( $c == 4) {
$style = 'thumbnail-fourth';
$c = 0;
}
else $style=''; ?> 

<div class="fastighet-thumbnail <?php echo($style) ?>" id="post-<?php the_ID(); ?>">
    <div class="fastighet-thumbnail-image">
        <a href="<?php the_permalink();?>"><?php the_post_thumbnail( 'admin-list-thumb', array( 'alt' => ''.get_the_title().'', 'title' => ''.get_the_title().'' )); ?></a> 
    </div>

    <div class="fastighet-title">
        <a href="<?php the_permalink();?>"><?php the_title(); ?></a>   
    </div>                                  
</div> <!-- end .fastighet-thumbnail -->

<?php $count++; if ( ( $count % 4 ) == 0 && $query->have_posts() ) { ?> 
<!-- if counter equals 4 then close the slide and open a new one -->
</li>
<li class="4slide">
<?php } endwhile; ?>
</li>
<?php endif; ?>     
<?php wp_reset_query(); ?>  
</ul>

Can anybody see what´s wrong with this? How I could modify it to allow me to use ‘posts_per_page’ like I should be?

Related posts

Leave a Reply

2 comments

  1. This is old but i’ll add the answer anyway for any future visitors

    The problem is that $query->have_posts() also do a cleanup & reset all the posts when there are no posts left to loop. When this function is called inside the main while loop as the if condition, it reset the posts & then when it’s called again in while condition, it starts the loop again from the beginning.

    To solve this problem, use $query->current_post + 1 != $query->post_count inside your if condition