如果您不知道WP_Query
類中的粘性帖子是如何工作的,那麼只查詢某些粘性帖子或試圖查看粘性帖子列表可能會非常棘手。
讓我們快速瀏覽一下膠粘如何在WP_Query
類中查詢
// Put sticky posts at the top of the posts array
$sticky_posts = get_option('sticky_posts');
if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) {
$num_posts = count($this->posts);
$sticky_offset = 0;
// Loop over posts and relocate stickies to the front.
for ($i = 0; $i < $num_posts; $i++) {
if (in_array($this->posts[$i]->ID, $sticky_posts)) {
$sticky_post = $this->posts[$i];
// Remove sticky from current position
array_splice($this->posts, $i, 1);
// Move to front, after other stickies
array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
// Increment the sticky offset. The next sticky will be placed at this offset.
$sticky_offset++;
// Remove post from sticky posts array
$offset = array_search($sticky_post->ID, $sticky_posts);
unset($sticky_posts[$offset]);
}
}
// If any posts have been excluded specifically, Ignore those that are sticky.
if (!empty($sticky_posts) && !empty($q['post__not_in']))
$sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
// Fetch sticky posts that weren't in the query results
if (!empty($sticky_posts)) {
$stickies = get_posts(array(
'post__in' => $sticky_posts,
'post_type' => $post_type,
'post_status' => 'publish',
'nopaging' => true
));
foreach ($stickies as $sticky_post) {
array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
$sticky_offset++;
}
}
}
正如你可以看到,如果我們傳遞正確的參數WP_Query
和is_home()
返回true,WP_Query
將返回所有置頂文章不管。當您使用post__in
參數時會發生這種情況。這意味着什麼,如果你只是有條件地查詢粘性帖子,不管你作爲參數傳遞了什麼,你總是會將所有粘性帖子返回到第一頁。要阻止這種情況發生,我們需要將ignore_sticky_posts
設置爲1
,以便我們避免查詢所有粘性帖子。
請注意post__in
。在傳遞任何東西給post__in
之前,您應該始終確保您有一個有效的帖子ID。如果你傳遞一個空數組,就像沒有粘性帖子一樣,所有的帖子都會返回,不管它是否如期望的那樣返回一個空數組,所以要注意這個
讓我們看看可能的解決方案(未經測試且要求PHP 5.4+)
// Get all sticky posts
$stickies = get_option('sticky_posts');
// Make sure we have sticky posts
if ($stickies) {
// We have stickies, lets set our query
$args = [
'post__in' => $stickies,
'ignore_sticky_posts' => 1,
'posts_per_page' => 5,
'paged' => get_query_var('paged', 1),
// Any other arguments
];
$q = new WP_Query($args);
// YOUR LOOP
while ($q->have_posts()) {
$q->the_post();
// YOUR OUTPUT
}
/**
* Lets use my pagination function
* @link http://wordpress.stackexchange.com/a/172818/31545
*/
if (function_exists('')) {
$paging_args = [
'query' => $q
];
echo get_paginated_numbers($paging_args);
}
wp_reset_postdata();
}
您需要在哪個頁面/模板上執行此操作。另外,爲了確保我明白,你只需要粘貼文章,非粘性文章應該被完全刪除 –
我需要這個爲我的特殊新聞頁面。基本上我們只想顯示某些帖子(粘性的),而不刪除其他不粘的帖子。 – toiletbowl
你一次會顯示多少貼子?看看這個:https://wordpress.org/plugins/sticky-slider/ - 有幫助嗎? – JamesG