$roles = get_editable_roles(); // Retrieve all user roles
foreach ($roles as $role_key => $role_details) {
$args = array(
'role' => $role_key,
'orderby' => 'login',
'order' => 'ASC',
);
$user_query = new WP_User_Query($args);
if (!empty($user_query->get_results())) {
echo '<h2>' . $role_details['name'] . '</h2>';
foreach ($user_query->get_results() as $user) {
$username = $user->user_login;
$post_count = count_user_posts($user->ID);
echo 'Username: ' . $username . ', Post Count: ' . $post_count . '<br>';
}
} else {
echo '<h2>' . $role_details['name'] . '</h2>';
echo 'No users found.';
}
}
get_editable_roles() function to retrieve an array of all user roles and their details. We then iterate through each role and perform a user query for that specific role. Inside the loop, we display the role name as a heading.