4

I have to get all the users whose first name starts with the letter "A". I get the user information by using the get_users() function. How can i use the argument query to get the users whose first name letter starts with "A"?

I used the function below

         <?php $users = get_users(array('role' => 'user_role', 
                                        'meta_key' => 'first_name',
                                        'meta_value' => 'A*',
                                        'meta_compare' => 'LIKE'));

I have found no results. Is there a mistake here?

4

3 に答える 3

5

を使用LIKEするには、meta_query

$args = array(
    'role' => 'user_role', 
    'meta_query' => array(
        array(
            'key' => 'first_name',
            'value' => array( 'A', 'B'),
            'compare' => 'BETWEEN'
        )
    )
);
$users= get_users($args);
于 2013-02-05T14:43:01.253 に答える
1

前述のように、LIKE を使用すると、文字が先頭にあるかどうかに関係なく、文字を含む任意の値に一致することを意味します。したがって、LIKE を使用しても、おそらく必要なものが得られません。

WordPress でのアプローチは、「BETWEEN」比較を使用しているようです。そのため、単語が 1 つの文字とそれに続く文字の間にある値と一致します。

http://www.essentialwp.com/tag/meta_query/のチュートリアルに従って、単語を開始する文字を取得し、PHP 機能を使用して後続の文字を見つけることができます。結果を正しくフィルタリングします。

// Get the value for surname and attach it to a variable
$letter = $_GET['surname'];]

// We need to establish the letter after the first letter from $letter, so in this case 'D'
$letterAfter = chr(ord($letter)+1);

// Craft a custom wp_query call
$args = array(
    'post_type' => 'profiles',  // use this if you are using a custom post type
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'surname', // name of your custom field
            'value' => array( $letter, $letterAfter ),
            'orderby' => 'meta_value',
            'compare' => 'BETWEEN',
            'order' => 'ASC'
        )
    )
 );
$wp_query = new WP_Query( $args );

// then run your loop....

Z の文字を別の方法で処理する必要がある可能性があります。「Z」の文字で始まる名でユーザーを取得するを参照してください</a>

PHP を使用してアルファベットの次の文字を取得する最も効率的な方法にも興味があるかもしれません

于 2014-07-15T05:28:36.557 に答える