我运行了一个包含作者帖子的博客网站,并且我实现了一个搜索,如果搜索像是作者的名字,或者搜索词包含在故事中,就会返回结果。我正常运行并正确返回与搜索匹配的作者,但现在搜索每次都返回每个用户。
我怀疑这与WP_User_query since
由于该函数在4.2中进行了更新,但我不知道如何将其更改为兼容。
以下是搜索代码:
add_filter(\'user_search_columns\', \'user_search_columns_bd\' , 10, 3);
function user_search_columns_bd($search_columns, $search, $this){
if(!in_array(\'display_name\', $search_columns)){
$search_columns[] = \'display_name\';
}
return $search_columns;
}
add_filter( \'get_meta_sql\', \'user_meta_filter\', 10, 6 );
function user_meta_filter( $sql, $queries, $type, $primary_table, $primary_id_column, $context ){
if ( $type !== \'user\' ){
return $sql;
}
if ( ! isset( $context->query_vars[\'meta_query\'][\'replace_and\'] ) || $context->query_vars[\'meta_query\'][\'replace_and\'] !== true ){
return $sql;
}
$sql[\'where\'] = preg_replace(\'/AND/\', \'OR\', $sql[\'where\'], 1);
return $sql;
}
$args = array(
\'search\' => $s,
\'search_columns\' => array( \'user_login\', \'user_email\'),
\'meta_query\' => array(
\'relation\' => \'OR\',
\'replace_and\' => true,
array(
\'key\' => \'first_name\',
\'value\' => $s,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'last_name\',
\'value\' => $s,
\'compare\' => \'LIKE\'
)
)
);
// The Query
$user_query = new WP_User_Query( $args );
SO网友:Wold
问题是由于在最新更新中重新构造了查询。正如d79在this question, 查询更改自:
SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND (user_login LIKE \'test\' OR user_email LIKE \'test\' OR display_name LIKE \'test\') OR (
(
(
( wp_usermeta.meta_key = \'first_name\' AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'%test%\' )
OR
( wp_usermeta.meta_key = \'last_name\' AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'%test%\' )
)
AND
mt1.meta_key = \'wp_6_capabilities\'
)
) ORDER BY user_login ASC
至
SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 OR (
(
(
( wp_usermeta.meta_key = \'first_name\' AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'%test%\' )
OR
( wp_usermeta.meta_key = \'last_name\' AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'%test%\' )
)
AND
mt1.meta_key = \'wp_6_capabilities\'
)
) AND (user_login LIKE \'test\' OR user_email LIKE \'test\' OR display_name LIKE \'test\') ORDER BY user_login ASC
因此,他的职能是:
add_action(\'pre_user_query\', \'my_custom_users_search\');
function my_custom_users_search( $args ) {
if( isset( $args->query_vars[\'meta_query\'][\'replace_and\'] ) && $args->query_vars[\'meta_query\'][\'replace_and\'] )
$args->query_where = str_replace(\') AND (\', \') OR (\', $args->query_where);
}
针对正确的
AND
要更改为
OR
. 他的解决方案为我解决了这个问题。