PHP/SQL/Wordpress: Group a user list by alphabet
- by rayne
I want to create a (fairly big) Wordpress user index with the users categorized alphabetically, like this:
A
Amy
Adam
B
Bernard
Bianca
and so on.
I've created a custom Wordpress query which works fine for this, except for one problem: It also displays "empty" letters, letters where there aren't any users whose name begins with that letter. I'd be glad if you could help me fix this code so that it only displays the letter if there's actually a user with a name of that letter :) I've tried my luck by checking how many results there are for that letter, but somehow that's not working.
(FYI, I use the user photo plugin and only want to show users in the list who have an approved picture, hence the stuff in the SQL query).
<?php
$alphabet = range('A', 'Z');
foreach ($alphabet as $letter) {
$user_count = $wpdb->get_results("SELECT COUNT(*) FROM wp_users WHERE display_name LIKE '".$letter."%' ORDER BY display_name ASC");
if ($user_count > 0) {
$user_row = $wpdb->get_results("SELECT wp_users.user_login, wp_users.display_name
FROM wp_users, wp_usermeta
WHERE wp_users.display_name LIKE '".$letter."%'
AND wp_usermeta.meta_key = 'userphoto_approvalstatus'
AND wp_usermeta.meta_value = '2'
AND wp_usermeta.user_id = wp_users.ID
ORDER BY wp_users.display_name ASC");
echo '<li class="letter">'.$letter.'';
echo '<ul>';
foreach ($user_row as $user) {
echo '<li><a href="/author/'.$user->user_login.'">'.$user->display_name.'</a></li>';
}
echo '</ul></li>';
}
}
?>
Thanks in advance!