请尝试以下操作:
NOTE: make sure to add any extra conditional logic you need for your usecase, such as a check for is_home()
and the value for get_query_var( \'paged\' )
. I have intentionally left those out just for brevity.
function custom_pre_get_posts_meta_query( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
$meta_key = \'caja\'; //meta_key to query
$query->set(
\'orderby\',
array(
\'meta_value\' => \'DESC\',
\'date\' => \'DESC\'
)
);
$query->set(
\'meta_query\',
array(
array(
\'key\' => $meta_key,
\'value\' => \'IGNORE THIS VALUE\', //this just needs to be something random
\'compare\' => \'NOT EXISTS\'
)
)
);
add_filter( \'posts_where\', \'custom_where_meta_query\' );
}
add_action( \'pre_get_posts\', \'custom_pre_get_posts_meta_query\', 1 );
function custom_where_meta_query( $where = \'\' ){
global $wpdb;
$meta_key = \'caja\'; //meta_key
$meta_values = array(\'uno\', \'dos\'); //meta_values
$sql = "\'" . implode( "\', \'", array_map( \'esc_sql\', $meta_values ) ) . "\'";
$where .= $wpdb->prepare(
" OR (( {$wpdb->postmeta}.meta_key = %s AND {$wpdb->postmeta}.meta_value IN ( {$sql} ) ))",
$meta_key
);
remove_filter( \'posts_where\', \'custom_where_meta_query\' );
return $where;
}
上的第一个回调函数
pre_get_posts
将启动
WP_Meta_Query
它构建了必要的SQL,然后在第二个回调函数中对其进行过滤。
结果首先由排序meta_value DESC
然后由date DESC
. 这将为元键分组两个匹配的帖子caja
在顶部,其余职位将按日期排序。
这避免了您必须在数据库中重新查询所需的两个特定帖子,然后拼接结果集,最后清除重复的结果集。