因此,我正在寻找一种获取最新帖子的方法,以便以与其他帖子不同的方式显示它。在设置中,我有我的“博客”页面来显示帖子,通常每个人都会这样做。
我尝试的第一件事(另一个问题的答案)是使用正常循环,我的意思是,if (have_posts())...while(have_posts())..etc。在该IF之上,放置另一个IF以获取最新帖子,通过这种方式我可以为我的最后一个帖子设置样式。但由于我有分页,在每个页面上,最新的帖子实际上是该页面的最新帖子,而不是真正的最新帖子。希望这是可以理解的。
我的第二次尝试是从正常循环中排除最新帖子,为此我使用了一篇文章中的片段,该文章解释了如何排除最新帖子并使用pre_get_posts和found_posts保持分页工作,因此我的代码如下:
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
//Before anything else, make sure this is the right query...
if ( ! $query->is_home() ) {
return;
}
//First, define your desired offset...
$offset = 1;
//Next, determine how many posts per page you want (we'll use WordPress's settings)
$ppp = get_option('posts_per_page');
//Next, detect and handle pagination...
if ( $query->is_paged ) {
//Manually determine page query offset (offset + current page (minus one) x posts per page)
$page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
//Apply adjust page offset
$query->set('offset', $page_offset );
}
else {
//This is the first page. Just use the offset...
$query->set('offset',$offset);
}
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
//Define our offset again...
$offset = 1;
//Ensure we're modifying the right query object...
if ( $query->is_home() ) {
//Reduce WordPress's found_posts count by the offset...
return $found_posts - $offset;
}
return $found_posts;
}
到目前为止一切顺利,这段代码正在运行,它不包括最新的帖子并且分页正在运行,但现在我的问题是,我如何获得最新的帖子?我尝试在home.php 中的循环上方使用wp_query来获取该单个最新帖子,但意识到pre_get_posts覆盖了wp_query?
我怎样才能解决这个问题并获得最新的帖子?我必须做相反的事情吗?我的意思是,首先获取最新帖子,然后为其余帖子创建自定义循环,但如何管理分页?
开心每一天1111