因此,我正在尋找一種獲取最新帖子的方法,以便以與其他帖子不同的方式顯示它。在設(shè)置中,我有我的“博客”頁(yè)面來(lái)顯示帖子,通常每個(gè)人都會(huì)這樣做。我嘗試的第一件事(另一個(gè)問題的答案)是使用正常循環(huán),我的意思是,if (have_posts())...while(have_posts())..etc。在該IF之上,放置另一個(gè)IF以獲取最新帖子,通過(guò)這種方式我可以為我的最后一個(gè)帖子設(shè)置樣式。但由于我有分頁(yè),在每個(gè)頁(yè)面上,最新的帖子實(shí)際上是該頁(yè)面的最新帖子,而不是真正的最新帖子。希望這是可以理解的。我的第二次嘗試是從正常循環(huán)中排除最新帖子,為此我使用了一篇文章中的片段,該文章解釋了如何排除最新帖子并使用pre_get_posts和found_posts保持分頁(yè)工作,因此我的代碼如下: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;}到目前為止一切順利,這段代碼正在運(yùn)行,它不包括最新的帖子并且分頁(yè)正在運(yùn)行,但現(xiàn)在我的問題是,我如何獲得最新的帖子?我嘗試在home.php 中的循環(huán)上方使用wp_query來(lái)獲取該單個(gè)最新帖子,但意識(shí)到pre_get_posts覆蓋了wp_query?我怎樣才能解決這個(gè)問題并獲得最新的帖子?我必須做相反的事情嗎?我的意思是,首先獲取最新帖子,然后為其余帖子創(chuàng)建自定義循環(huán),但如何管理分頁(yè)?
獲取博客頁(yè)面上的最新帖子
繁華開滿天機(jī)
2021-09-05 20:45:33