I'm trying to query WP Users and group them by billing_state
, a custom meta key/value but I'm getting some unexpected results where it gives me some empty options but also is only returning one result per billing_state
.
Based on some research on SO it was suggested I query all users and then create a new array where I can set the state as the array key then the user object as the value.
Here is what I tried:
add_shortcode('pro_pro_users','pro_pro_users');
function pro_pro_users(){
global $wpdb;
$user_query = new WP_User_Query( array( 'fields' => 'all' ) );
$users = $user_query->get_results();
if (!empty($users)) {
$usersByState = array();
foreach ($users as $user) {
$usersByState[get_user_meta($user->ID, 'billing_state', true)] = $user;
}
foreach ($usersByState as $k => $v){
if(!empty($v)) {
echo '<li><h5>' . $k . '</h5>';
echo '<ul>';
foreach ($v as $user) {
echo '<li><a href="' . get_author_posts_url($user->ID) . '">' . get_user_meta($user->ID, 'first_name', true) . ' ' . get_user_meta($user->ID, 'last_name', true) . ' (' . $user->display_name . ')</a></li>';
}
echo '</ul>';
echo '</li>';
}
}
echo '</ul>';
} else {
echo 'No users found';
}
}
Here is what is happening (note the empty ones and only one per state although I know some of these have more than one
I've checked:
https://codex.wordpress.org/Class_Reference/WP_User_Query https://codex.wordpress.org/Database_Description#Table:_wp_users https://codex.wordpress.org/Function_Reference/get_users https://wordpress.stackexchange.com/questions/105937/group-posts-by-meta-key https://wordpress.stackexchange.com/questions/205427/group-posts-by-attachment-meta-key https://usersinsights.com/wordpress-user-meta-query/