将元查询与关键字搜索相结合将返回与搜索查询和元查询结果都匹配的帖子(即使您使用relation => OR
在元查询中)。
This answer 介绍了一种实现帖子预期结果的方法,您需要在查询获取结果之前修改查询。但是,需要对其进行修改,以便与WP用户查询一起使用。我尝试了一种在user_nicename
, user_email
和您的元字段-未经测试,因此可能需要调整。
add_action( \'pre_user_query\', \'user_meta_OR_search\');
function user_meta_OR_search($q){
if ($search = $q->get(\'_meta_or_search\')){
add_filter( \'get_meta_sql\', function( $sql ) use ( $search ){
global $wpdb;
// Only run once:
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// Modify WHERE part:
$where = sprintf(
" AND ( %s OR %s OR %s ) ",
$wpdb->prepare( "{$wpdb->users}.user_nicename like \'%%%s%%\'", $search),
$wpdb->prepare( "{$wpdb->users}.user_email like \'%%%s%%\'", $search),
mb_substr( $sql[\'where\'], 5, mb_strlen( $sql[\'where\'] ) )
);
$sql[\'where\'] = $where;
return $sql;
});
}
}
// Then, where you do the searching:
$search_term = "test";
$args = array(
\'fields\' => [\'ID\'],
\'count_total\' => true,
\'order\' => \'ASC\',
\'orderby\' => \'display_name\',
\'_meta_or_search\' => \'*\'.esc_attr( $search_term ).\'*\',
"meta_query" => array(
\'relation\' => \'OR\',
array(
\'key\' => \'first_name\',
\'value\' => $search_term,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'last_name\',
\'value\' => $search_term,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'description\',
\'value\' => $search_term ,
\'compare\' => \'LIKE\'
)
)
);
$the_query = new WP_User_Query($args);
另一种解决方案是使用两个查询–一个是使用
s
和一个搜索使用
meta_query
:
$args1 = array (
\'fields\' => [\'ID\'],
\'count_total\' => true,
\'order\' => \'ASC\',
\'orderby\' => \'display_name\',
\'search\' => \'*\'.esc_attr( $search_term ).\'*\'
);
$wp_user_query1 = new WP_User_Query($args1);
$args2 = array (
\'fields\' => [\'ID\'],
\'count_total\' => true,
\'order\' => \'ASC\',
\'orderby\' => \'display_name\',
\'meta_query\' => array(
\'relation\' => \'OR\',
array(
\'key\' => \'first_name\',
\'value\' => $search_term,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'last_name\',
\'value\' => $search_term,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'description\',
\'value\' => $search_term ,
\'compare\' => \'LIKE\'
)
)
);
$wp_user_query2 = new WP_User_Query($args2);
$result = new WP_User_Query();
$result->results = array_unique( array_merge( $wp_user_query1->results, $wp_user_query2->results ), SORT_REGULAR );
$result->post_count = count( $result->results );
这将把两个查询的结果合并到包含最终搜索结果的第三个查询中。我还没有测试过这个,所以它可能需要一些调整!