0

This is my script which lists all the roles...

function all_the__roles() {
    global $wp_roles;
    $the_roles = $wp_roles->get_names();
    $roles = '';
    $role_count = '';
    foreach($the_roles as $role) {
        $roles .= $role . '<br />';
        $role_count++;
    }
    return $roles;
}

echo all_the__roles();

If I change return $roles; to return $role_count; then I get the number of roles.

Is there a way I can have both without writing an additional separate function? I want to list the roles and also the number roles. So the output could be something like:

Administrator
Editor
Client
3

Cheers.

User_FTW
  • 504
  • 1
  • 16
  • 44
  • personally I wouldn't bother with a function for this you can do `$the_roles = $wp_roles->get_names();` and then do `implode('
    ', $the_roles )` or `count($the_roles)` etc. And then there is no reason making a function for it. Otherwise do `return ['roles' => implode('
    ', $the_roles ), 'count' => count($the_roles)]` and remove the `foreach` -6 lines of code.
    – ArtisticPhoenix Mar 09 '19 at 09:39

1 Answers1

0

Please try this one

function all_the__roles() {
    global $wp_roles;
    $the_roles = $wp_roles->get_names();
    $roles = '';
    $role_count = 0;
    foreach($the_roles as $role) {
        $roles .= $role . '<br />';
        $role_count++;
    }

    if($role_count > 0){
        $roles .= $role_count . '<br />';
    }

    return $roles;
}

echo all_the__roles();
Prince
  • 176
  • 8
  • That works, but it's not exactly what I need. I probably could have explained it better. Somewhere in the document I might want to list the roles, and somewhere else in the document I might want to display the number of roles. So I need the function to offer me a way to do either in any part of the document. – User_FTW Mar 09 '19 at 08:39
  • yes try this one function all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); $role_count = 0; $data = array(); foreach($the_roles as $role) { $data['roles'][] = $role; $role_count++; } if($role_count > 0){ $data['roles'] = $role_count; } return $data; } print_r(all_the__roles()); – Prince Mar 09 '19 at 09:41
  • all they need is this `function all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); return ['roles' => implode('
    ', $the_roles ), 'count' => count($the_roles)]; }`
    – ArtisticPhoenix Mar 09 '19 at 09:44
  • function all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); $role_count = 0; $data = array(); foreach($the_roles as $role) { $data['roles'][] = $role; $role_count++; } if($role_count > 0){ $data['roles_count'] = $role_count; } return $data; } $roles_data = all_the__roles(); $roles = $roles_data['roles']; // or $roles = implode("
    ",$roles); $roles_count = $roles_data['roles_count'];
    – Prince Mar 09 '19 at 09:48