WordPress VIP 和其他development guides 我看到过这样的建议:在大规模使用WordPress时,出于性能原因,避免使用post\\u not\\u in。他们的建议是过滤掉php中的帖子:
$posts_to_exclude = [ 67, 68, 69 ];
$query = new WP_Query( [
\'post_type\' => \'post\',
\'posts_per_page\' => 5 + count( $posts_to_exclude ),
\'paged\' => get_query_var( \'paged\' ),
] );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
if ( in_array( get_the_ID(), $posts_to_exclude, true ) ) {
continue;
}
the_title();
endwhile;
endif;
我的问题是,在通过php过滤帖子时,如何显示每页正确的帖子数量?上面的示例将排除帖子的计数添加到posts\\u per\\u page变量中。然而,这将导致每页有5-8篇文章,这取决于某一特定页面排除的文章数量。是否有一个可行的解决方案可以使每页的帖子数量保持一致,或者这种优化只针对那些不需要分页的帖子?
SO网友:Sebastian Kurzynowski
如果你想保持posts
限制和避免参数post_not_in
您应该将这些代码添加到筛选器posts
在里面$query
.
//get posts from query object
$posts = $query->posts;
//set limit of posts that You need on page
$limit = 5;
//filter by ID that You want to exclude
$posts = array_filter($posts, function( $data ){
if( ! in_array( $data->ID, $posts_to_exclude ) )return true;
});
$posts = array_slice($posts, 0, $limit);
//put filtered posts in query object
$query->posts = $posts;
//here You can do Your loop
SO网友:Sebastian Kurzynowski
$limit = 5;
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
if ( in_array( get_the_ID(), $posts_to_exclude, true ) && $limit > 0 ) {
continue;
}
$limit--;
the_title();
endwhile;
endif;