而循环创造了一个无限循环


While cycle create an infinite loop

我写这段PHP代码是为了放在wordpress页面模板上:

<?php 
query_posts('showposts=10&cat=7'); 
while (have_posts()) : the_post(); 
?> 
<li class="img-slider"> 
    <?php the_content(); ?> 
</li> 
<?php endwhile; ?> 

当我查看页面时,我看不到任何结果,浏览器的右栏继续缩小。我知道代码会创建一个无限循环。我哪里搞错了?

感谢

首先,您不应该使用query_posts。对于简单的循环来说,它的侵入性太强,并且会扰乱整个WP_Query。此外,showposts应该是posts_per_page

其次,如果没有更多的上下文,很难判断这个问题是什么。也许可以粘贴你的整个页面,并将其编辑成你的问题。我的猜测是循环中的一个循环,应该停在大约100个帖子上。(10 X 10),但如果它在其他地方重置,那么它很可能会无限!

使用此代码来创建循环:

$custom_query = new WP_Query( 'posts_per_page=10' );
if($custom_query->have_posts()) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        //global $post; // for stuff like $post->post_name
        // Post stuff here
        // the_title();
    endwhile;
endif;
// Reset Post Data
wp_reset_postdata();

查看WordPress代码以了解更多详细信息。http://codex.wordpress.org/Class_Reference/WP_Query#Parameters

您应该在循环中使用if语句:

<?php 
query_posts('showposts=10&cat=7'); 
if ( have_posts() ): while ( have_posts() ) : the_post(); 
?> 
<li class="img-slider"> 
    <?php the_content(); ?> 
</li> 
<?php endwhile; endif; ?> 

如果没有更多信息,我会说在while语句的每个循环中,函数都返回数据的第一行?因此,每次while循环执行时,您都会再次调用该函数,即一次又一次地返回相同的一路领先,而无需实际迭代结果集。