我认为唯一的解决方案是跳过sql分页,只通过php处理它。我的想法包括两个功能,一个连接pre_get_posts
, 要筛选的第二个the_posts
.
第一个函数做两件事:
取消设置搜索的分页值,这样所有帖子都将从SQL查询返回保存查询的paged
全局变量中的值,以这种方式可以在稍后运行的第二个函数中使用此函数:
function filter_my_search_query( $query ) {
if ( is_search() && $query->is_main_query() && ! is_admin() ) {
global $the_original_paged;
$the_original_paged = $query->get(\'paged\') ? $query->get(\'paged\') : 1;
$query->set(\'paged\', NULL );
$query->set(\'nopaging\', TRUE );
}
}
add_action(\'pre_get_posts\', \'filter_my_search_query\', 1);
现在,搜索查询返回所有帖子,不分页,所需分页保存在全局变量中
$the_original_paged
.
所以我们可以过滤the_posts
合并想要的其他帖子,然后根据所需页面和每页帖子设置仅获取正确的帖子,最后重置paged
和其他$wp_query
让分页链接工作的属性:
function add_posts_to_search_query( $posts ) {
global $wp_query, $the_original_paged;
if ( ! is_main_query() || is_admin() || ! is_search() || is_null($the_original_paged) )
return $posts;
// the wanted posts per page here setted on general settings
$perpage = get_option(\'posts_per_page\');
remove_filter( \'the_posts\', \'add_posts_to_search_query\' );
$new = new WP_Query( \'year=2012&monthnum=12&day=12&nopaging=1\' );
$merged = array_merge( $posts, $new->posts );
$wp_query->found_posts += $new->found_posts;
// getting the right posts based on current page and posts per page
$wp_query->posts = array_slice($merged, ( $perpage * ($the_original_paged-1) ), $perpage );
// set the paged and other wp_query properties to the right value, to make pagination work
$wp_query->set(\'paged\', $the_original_paged);
$wp_query->post_count = count($wp_query->posts);
$wp_query->max_num_pages = ceil( $wp_query->found_posts / $perpage );
unset($the_original_paged); // clean up global variable
return $wp_query->posts;
}
add_filter(\'the_posts\', \'add_posts_to_search_query\');