我有一个大问题。是否可以对两个循环使用分页。我的代码是
<div class="first_div">
<?php
if (have_posts()) :
$count = 0;
while (have_posts()) : the_post();
$count++;
if ($count == 1) :
the_title();
elseif ($count == 2) :
the_title();
elseif ($count == 3) :
the_title();
endif;
endwhile;
endif;
?>
</div>
<div class="second_div">
<h3>Div between first_div and third_div</h3>
</div>
<div class="third_div">
<?php
query_posts( array('posts_per_page'=>4,'offset'=>3) );
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
</div>
从上面的代码中,我需要显示总共7条最新消息。first_div中的3个和third_div中剩余的4个。而且效果很好。所以,现在我需要做的是,我需要在第三个div之后进行分页。但实际上我需要一个介于first_div和third_div之间的div。因此,我无法在third_div之后创建分页。是否可以提供分页
正如我在上面的评论中所说,这一切都可以在一个查询中完成。
在我深入研究之前,有一个重要的注意事项,永远不要使用query_posts
注意:此函数不适用于插件或主题。正如后面所解释的,有更好、更高性能的选项来更改主查询。query_posts()是一种过于简单且有问题的修改页面主查询的方法,将其替换为新的查询实例。它效率低下(重新运行SQL查询),在某些情况下会完全失败(尤其是在处理后分页时)。
(CAVEAT:这是未经测试的,但应该有效)
好的,下面是我们将如何进行
-
正常运行循环。我们将使用内置循环计数器(
$current_post
,记住,它从0
开始,而不是从1
开始)来计算我们的帖子,然后根据这个,做一些 -
在我们的第一次运行中,我们将跳过帖子4-7,只在div 1 中显示前三个
-
在循环的第一次运行之后,我们将在div 2 中显示分页
-
为了显示帖子4-7,我们需要倒带我们的循环,并运行第二次
-
在第二次运行中,我们将跳过前三个帖子,只在div 3 中显示帖子4-7
现在,让我们开始编码
1.)正常运行循环,排除/跳过4-7个
if( have_posts() ) {
while( have_posts() ) {
the_post();
if( 0 === $wp_query->current_post ) {
echo '<div class="first_div">'; // Open our div container only if it is the first post
}
the_title();
if ( 2 === $wp_query->current_post ) {
echo '</div>'; // Close our div container after post three
}
if( 3 >= $wp_query->current_post ) {
//finish of the loop but displays nothing from posts 4 - 7
}
}
}
2.)按照正常添加我们的分页
<div class="second_div">
<h3>Div between first_div and third_div</h3>
</div>
3.)回放循环,以便我们可以重新运行
rewind_posts();
4.)重新运行循环,只显示4-7个
if( have_posts() ) {
while( have_posts() ) {
the_post();
if( 2 <= $wp_query->current_post ) {
//Skip posts 4 - 7 and displays nothing
}
if( 3 === $wp_query->current_post ) {
echo '<div class="third_div">'; // Open our div container only if it is the fourth post
}
the_title();
if ( 6 === $wp_query->current_post ) {
echo '</div>'; // Close our div container after post seven
}
}
}
应该是