問題描述
我正在使用 pre_get_posts 來調整我主頁上顯示的帖子數量。
function lifelounge_query_adjust( $query ) {
if ( is_home() ) {
set_query_var( 'posts_per_page', 12 );
return;
}
}
add_filter( 'pre_get_posts', 'lifelounge_query_adjust' );
但是我遇到了一個貼上帖子的問題。基本上,如果我有任何貼上的帖子,查詢將顯示超過我指定的 12 個帖子,因為它會顯示 12 加上任何貼上的帖子。當然,我可以忽略貼上的帖子:
function lifelounge_query_adjust( $query ) {
if ( is_home() ) {
set_query_var( 'posts_per_page', 1 );
set_query_var( 'ignore_sticky_posts', 1 );
return;
}
}
add_filter( 'pre_get_posts', 'lifelounge_query_adjust' );
但我不認為這是理想的。我認為貼上的帖子應該包含在 12 個帖子的限制內,而不是新增到限制。這是對我來說最有意義的。有辦法實現嗎?我做了一個 face-palm-worthy 錯誤?
幾乎是一個重複的:Sticky Posts & Posts Per Page,但這是非常關閉,太本地化了。我不同意,顯然是因為我正在尋找一個答案,也是因為這是一個問題,為什麼 WordPress 似乎不尊重 posts_per_page 限制,如果你使用貼上的帖子。如果你想要每頁 12 個帖子,你應該得到 12,而不是 13,這是你會得到,如果你有一個貼上的帖子。
最佳解決方案
這是一個透過獲取粘性帖子數量 (如果有的話) 來解釋貼上帖子的方法,並將其包含在計算 posts_per_page 引數中:
add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {
if ($query->is_main_query() && is_home()) {
// set the number of posts per page
$posts_per_page = 12;
// get sticky posts array
$sticky_posts = get_option( 'sticky_posts' );
// if we have any sticky posts and we are at the first page
if (is_array($sticky_posts) && !$query->is_paged()) {
// counnt the number of sticky posts
$sticky_count = count($sticky_posts);
// and if the number of sticky posts is less than
// the number we want to set:
if ($sticky_count < $posts_per_page) {
$query->set('posts_per_page', $posts_per_page - $sticky_count);
// if the number of sticky posts is greater than or equal
// the number of pages we want to set:
} else {
$query->set('posts_per_page', 1);
}
// fallback in case we have no sticky posts
// and we are not on the first page
} else {
$query->set('posts_per_page', $posts_per_page);
}
}
}
Edit
在我們希望設定的頁面數量小於或等於粘性帖子數量的情況下,我將 posts_per_page 設定為 1,這將導致 13 個或更多帖子 $sticky_count + 1(在這種情況下) 僅在第一頁 (後續頁面將有 12 個帖子) 。也許這是可以的,因為這種情況是罕見的,第一頁上的+1 帖子可能不那麼重要。
這是因為 Wordpress 將首先顯示所有貼上的帖子 (第一頁),即使它們的數量大於 posts_per_page 引數,因此我們將 posts_per_page 設定為 1 的最小量,因為 0 和負值將停用 posts_per_page 引數,這將使 Wordpress 顯示第一頁上的所有帖子。
參考文獻
注:本文內容整合自 google/baidu/bing 翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:gxnotes#qq.com(#替換為 @) 。