To retrieve a list of all users from WordPress, excluding those with the ‘bbp_blocked’ role, and sort them alphabetically based on their display name, you can use the following PHP code:
write the following code in the function.php
// Step 1: Create a Custom Endpoint fetching all users by akhil
function custom_users_endpoint() {
register_rest_route('custom/v1', '/all-users/', array(
'methods' => 'GET',
'callback' => 'get_all_users',
));
}
add_action('rest_api_init', 'custom_users_endpoint');
// Step 2: Define the Callback Function
function get_all_users() {
// Retrieve all users
$users = get_users();
$formatted_users = array();
// Sort users alphabetically based on display name
usort($users, function ($a, $b) {
return strcasecmp($a->display_name, $b->display_name);
});
foreach ($users as $user) {
// Skip users with the 'bbp_blocked' role
if (in_array('bbp_blocked', $user->roles)) {
continue;
}
// Format user data
$formatted_users[] = array(
'id' => $user->ID,
'username' => $user->user_login,
'name' => $user->display_name,
'email' => $user->user_email,
'role' => implode(', ', $user->roles),
// Add any other user data you want to include
);
}
// Ensure a RESTful response
return rest_ensure_response($formatted_users);
}
Now, the get_all_users the function can be accessed at the following endpoint,
http://yoursite.com/wp-json/custom/v1/get-all-users/