1

How can I show a list of Users with alphabetical headings? For example:

A
Adam
Alan

B
Bill
Bob

I've found examples that do it with Posts, but I can't figure out how to make it work with WP_User_query() :(

  • Are you looking to use listed first/last names or usernames? – mor7ifer Mar 7 '12 at 18:06
  • First names, please. They will always be present, in my particular setup it's a required field. – thv20 Mar 8 '12 at 10:31
0

After a good bit of tinkering I've come up with something. It's certainly not the BEST method, but since there's not a good way to do it through the core directly without having to do a bunch of array-reordering, I think SQL is a better solution here. Anyways, the SQL is as follows:

SELECT users.*, meta.meta_value
FROM $wpdb->users AS users LEFT JOIN $wpdb->usermeta AS meta
    ON users.ID = meta.user_id
WHERE meta.meta_key = 'first_name'
    AND meta.meta_value != ''
ORDER BY meta.meta_value ASC

Nothing special going on there, it just gets all the values from the users table where there's a first name set.

For the list you can just iterate through those results, it's pretty simple to do that. The only thing that you will need to do is get the headings to work right. If you store the heading, then do a case-insensitive compare, this should be pretty easy. For example (pseudocode):

$cur_first_letter = substr( $first_name, 0, 1 );

if( strtoupper( $cur_first_letter ) != strtoupper( $prev_first_letter ) ) {
    // output header for strtoupper( $cur_first_letter )
}

$prev_first_letter = $cur_first_letter;

Note: The SQL is tested, the PHP is not (obviously, since it's pseudocode).

  • If this was the solution, make sure you mark it as such. – mor7ifer Mar 8 '12 at 15:31
  • Already done – thanks again for your help.I added a new message below that's immediately usable, but yours will remain the accepted answer. – thv20 Mar 8 '12 at 15:37
5

@m0r7if3r provided the correct answer. For the sake of providing a directly usable snippet to anyone else looking at this issue, here's what I ended up using.

$wp_users = $wpdb->get_results("
    SELECT users.*, meta.meta_value
    FROM $wpdb->users AS users LEFT JOIN $wpdb->usermeta AS meta
        ON users.ID = meta.user_id
    WHERE meta.meta_key = 'first_name'
        AND meta.meta_value != ''
    ORDER BY meta.meta_value ASC
");

foreach ($wp_users as $wp_user) :

    $cur_first_letter = substr( $wp_user->meta_value, 0, 1 );

    if( strtoupper( $cur_first_letter ) != strtoupper( $prev_first_letter ) ) {
        echo "<h3 class='alpha-heading'>$cur_first_letter</h3>";
    }

    echo "<li><a href=''>$wp_user->meta_value</a></li>";

    $prev_first_letter = $cur_first_letter;

endforeach;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.