我需要在新闻档案页上翻页。如果在同一页上显示所有记录,则数据正确。但如果添加分页代码,则分页值(如1,2,3,…16)正确,但如果单击第2页,则显示与第1页相同的文章标题。
<h1 style="margin-left:10px;">News</h1>
<ul class="years">
<?php
$paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
$all_posts = get_posts(array(
\'post_type\' => \'news\',
\'posts_per_page\' => 20,
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'paged=\'. $paged,
));
// this variable will contain all the posts in a associative array
// with three levels, for every year, month and posts.
$ordered_posts = array();
foreach ($all_posts as $single) {
$year = mysql2date(\'Y\', $single->post_date);
$month = mysql2date(\'F\', $single->post_date);
// specifies the position of the current post
$ordered_posts[$year][$month][] = $single;
}
// iterates the years
foreach ($ordered_posts as $year => $months) { ?>
<li>
<h3><?php echo $year ?></h3>
<ul class="months">
<?php foreach ($months as $month => $posts ) { // iterates the moths ?>
<li>
<h3><?php printf("%s (%d)", $month, count($months[$month])) ?></h3>
<ul class="posts">
<?php foreach ($posts as $single ) { // iterates the posts ?>
<li>
<?php echo mysql2date(\'F j\', $single->post_date) ?> <a href="<?php echo get_permalink($single->ID); ?>"><?php echo get_the_title($single->ID); ?></a> (<?php echo $single->comment_count ?>)</li>
</li>
<?php } // ends foreach $posts ?>
</ul> <!-- ul.posts -->
</li>
<?php } // ends foreach for $months ?>
</ul> <!-- ul.months -->
<?php if(function_exists(\'wp_paginate\')) {
wp_paginate();
} ?>
</li> <?php
} // ends foreach for $ordered_posts
?>
</ul><!-- ul.years -->
以下是屏幕截图:-
SO网友:Lucio Coire Galibone
使用自定义get_posts()
您正在忽略$paged
这样,您将始终看到来自第一页的帖子。
根据Codex Page 如果希望在执行主查询之前对其进行更改,可以使用pre_get_posts
.
function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
$query->set(\'posts_per_page\', 10);
$query->set(\'post_type\', array(\'news\'));
$query->set(\'orderby\', \'date\');
$query->set(\'order\', \'DESC\');
}
}
add_action( \'pre_get_posts\', \'my_post_queries\' );
这样
$paged
var是从主查询维护的。
您还可以在hook函数中检查主查询是否在特定的归档文件或其他文件中。