问题是您不能使用LIKE
如你所述的比较。生成的SQL
将沿着以下路线查看:
AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'%B%\'
这意味着查询设置为查找每个字母
B
在我们的情况下。当然这不是你想要的,你需要的是这样的东西:
AND CAST(wp_usermeta.meta_value AS CHAR) LIKE \'B%\'
以便只进行搜索
starting with 这个
B
信
好消息是,你仍然可以实现你所需要的,但代价是看起来有点像黑客
这个WP_User_Query
:
$args = array(
\'meta_key\' => \'last_name\',
\'meta_value\' => \'B########\', // The \'########\' sequence acts sort of like an unique identifier
\'meta_compare\' => \'LIKE\',
);
$wt_user_query = new WP_User_Query( $args );
并且在
functions.php
我们在
get_meta_sql
过滤并更改
WHERE
条款:
function wt_custom_meta_sql( $sql ) {
/*
Search for that funky so called unique identifier
that we used to initialize our `WP_User_Query\' object
*/
$uid = \'########\';
preg_match( "/\'(%[^\']+{$uid}%)\'/", $sql[\'where\'], $matches );
if ( ! empty( $matches ) ) {
/*
We\'ve found it and now we get rid of the
extra \'%\' character as well as our identifier
*/
$val = str_replace( "{$uid}%", "%", ltrim( $matches[1], \'%\' ) );
$sql[\'where\'] = str_replace( $matches[0], "\'{$val}\'", $sql[\'where\'] );
}
return $sql;
}
add_filter( \'get_meta_sql\' , \'wt_custom_meta_sql\', 40 );