我已经为我的一个页面启用了分页功能,我正在从中提取最新的新闻文章。代码如下:
<div class="container white" style="padding:50px 0;">
<div class="container-max">
<?php
$paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : \'1\';
$args = array(
\'numberposts\' => 5,
\'offset\' => 2,
\'post_status\'=>"publish",
\'post_type\'=>"post",
\'orderby\'=>"post_date",
\'cat\'=>\'-8, -9, -7, -6, -5, -4\',
\'paged\'=> $paged
);
$postslist = get_posts( $args );
?>
<div class="latest_new_posts main-news">
<?php
$wp_query = new WP_Query(\'$args\'.$paged);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : the_post();
foreach ($postslist as $post) : setup_postdata($post);
?>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="position:relative; margin:45px 0;" > <div class="blog-date-news main-news-date"><span><?php the_date(\'d/m/Y\'); ?></span></div> <div class="blog-container main-news-container"> <div class="news-blog-title"><span><?php the_title(); ?></span></div> <div class="news-blog-excerpt"> <?php echo excerpt(500); ?> </div> <div class="news-blog-more main-news-blog-more"><a href="<?php the_permalink(); ?>"> <img src=""/></a></div> </div> </div>
<?php
endforeach;
endwhile;
?>
正如你所看到的,我已经
\'offset\' => 2
因为前两篇文章不应该显示。然而,现在这项工作开始了,当你转到第二页时,第一页的最后两篇帖子再次显示出来。例如,我在第1页上有4篇帖子:帖子A、帖子B、帖子C和第二页上的帖子,然后会显示:帖子C、帖子D、帖子E、帖子F
从第二页转到第三页时不会发生这种情况。
有人知道怎么解决这个问题吗?
SO网友:Arpan Sagar
您可以尝试使用此代码。它工作完美,已经过测试。
<?php
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
if ($paged == "1") {
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'offset\' => 0,
\'posts_per_page\' => 5
);
} else {
$offset = $paged * 5;
$offset = $offset - 5;
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'offset\' => $offset,
\'posts_per_page\' => 5
);
}
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
/*Your Code */
endwhile;
?>
<div class="pagination-grp">
<?php
$big = 999999999; // need an unlikely integer
//$i=1;
echo paginate_links(array(
\'base\' => str_replace($big, \'%#%\', esc_url(get_pagenum_link($big))),
\'format\' => \'?paged=%#%\',
\'current\' => max(1, get_query_var(\'paged\')),
\'prev_text\' => __(\'<\'),
\'next_text\' => __(\'>\'),
\'total\' => $loop->max_num_pages
));
wp_reset_postdata();
endif;
?>
</div>