Why am I getting an infinite loop with have_posts?

I have the following code, which causes an infinite loop for some reason. Can anybody explain what's going on please?

Thanks!

?php 

$flagged_stores = new WP_Query( array ( 'post_type' = 'store', 'orderby' = 'post_id', 'meta_key' = 'flagged', 'limit' = 10 ) );

   if($flagged_stores-have_posts()): ? 
        div class="table"
            table class="form-table"
                tr
                    thStore/th
                    thFlag Reason/th
                    thDelete Flag/th
                /tr
                ?php while($flagged_stores-have_posts()): ?
                    td?php echo the_title(); ?/td
                    td?php// echo get_post_custom_values('flagged'); ?/td
                    td?php// echo "Delete"; ?/td
                ?php endwhile;?
            /table
    ?php else: ?
            No flags found.
    ?php endif; ?

Topic recursive loop post-meta Wordpress

Category Web


As pointed out by Michael in a comment to brownian, use while and don't forget $your_query->the_post(); that iterates the post index. Wrap while in if($your_query->have_posts()) to have an option for no entries.

<?php
if($flagged_stores->have_posts()):
 while($flagged_stores->have_posts()):
  $flagged_stores->the_post(); 
  ?> 
    <!-- your html -->
  <?php 
 endwhile;
else: 
 ?>
 No flags found.
 <?php 
endif; 
?>

Look at this answer: get custom post type by tag

I believe you'd use $flagged_stores->the_post() inside while loop.


I do not know if this is what caused the infinite loop, but your WP_Query is off.

$flagged_stores = new WP_Query( array ( 'post_type' => 'store', 'orderby' => 'ID', 'meta_key' => 'flagged', 'posts_per_page' => 10 ) );

I updated 'orderby' and 'posts_per_page'.


try and use 'posts_per_page' instead of 'limit' - http://codex.wordpress.org/Class_Reference/WP_Query#Parameters

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.