为了使这一点更加完整,以下是我在评论中回答当前问题时所说的话
只是为了快速解释一下WP_Query
在某些情况下会发生灾难性的失败,其中空数组被传递给它的一些参数,而不是像我们预期的那样返回空数组WP_Query
返回所有帖子。至于获得正确的粘性,正如我之前所说的,您需要获得当前的类别id,并使用它来过滤粘性帖子。记住,使用这种方法时,需要从主查询中删除粘性帖子,否则会得到重复的帖子
作为一种替代解决方案,在主查询上使用挂钩和过滤器,并从similar question/answer, 这就是我想到的:(代码有很好的注释,因此可以遵循。注意:这还没有经过测试,至少需要PHP 5.4+)
function get_term_sticky_posts()
{
// First check if we are on a category page, if not, return false
if ( !is_category() )
return false;
// Secondly, check if we have stickies, return false on failure
$stickies = get_option( \'sticky_posts\' );
if ( !$stickies )
return false;
// OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID
$current_object = get_queried_object_id();
// Create the query to get category specific stickies, just get post ID\'s though
$args = [
\'nopaging\' => true,
\'post__in\' => $stickies,
\'cat\' => $current_object,
\'ignore_sticky_posts\' => 1,
\'fields\' => \'ids\'
];
$q = get_posts( $args );
return $q;
}
add_action( \'pre_get_posts\', function ( $q )
{
if ( !is_admin() // IMPORTANT, make sure to target front end only
&& $q->is_main_query() // IMPORTANT, make sure we only target the main query
&& $q->is_category() // Only target category archives
) {
// Check if our function to get term related stickies exists to avoid fatal errors
if ( function_exists( \'get_term_sticky_posts\' ) ) {
// check if we have stickies
$stickies = get_term_sticky_posts();
if ( $stickies ) {
// Remove stickies from the main query to avoid duplicates
$q->set( \'post__not_in\', $stickies );
// Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages
if ( !$q->is_paged() ) {
// Add stickies via the the_posts filter
add_filter( \'the_posts\', function ( $posts ) use ( $stickies )
{
$term_stickies = get_posts( [\'post__in\' => $stickies, \'nopaging\' => true] );
$posts = array_merge( $term_stickies, $posts );
return $posts;
}, 10, 1 );
}
}
}
}
});
少数注意事项:此选项仅适用于默认设置
category
分类学代码可以很容易地修改(请这样做,根据您的需要进行修改),以使用任何分类法及其相关术语
您只需将其添加到函数中即可。php。无需更改模板文件或使用自定义查询。您所需要的只是带有默认循环的主查询
上述代码现在已在Wordpress 4.2.1和PHP 5.4上进行了测试和使用+