Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress list user roles

Tags:

wordpress

I am working ion a wordpress project and digging around into roles etc.

I have the following code which basically gets all available roles:

<?php 
     global $wp_roles;
     $roles = $wp_roles->get_names();

     // Below code will print the all list of roles.
     print_r($roles);        
?>

when i run the above code i get the following output:

array ( [administrator] => Administrator [editor] => Editor [author] => Author [contributor] => Contributor [subscriber] => Subscriber [basic_contributor] => Basic Contributor  ) 

i would like the above to be stripped from the array and into just an unordered list. How would i achieve this?

Thanks Dan

like image 817
danyo Avatar asked Oct 31 '12 16:10

danyo


4 Answers

You can use a foreach loop, to loop through each of the roles in the array.

<ul>
<?php foreach($roles as $role) { ?>
   <li><?php echo $role;?></li>
<?php }//end foreach ?>
</ul>
like image 104
Marty Avatar answered Oct 09 '22 11:10

Marty


Here is the code to make dropdown of wordpress user role

<?php global $wp_roles; ?>

<select name="role">
<?php foreach ( $wp_roles->roles as $key=>$value ): ?>
<option value="<?php echo $key; ?>"><?php echo $value['name']; ?></option>
<?php endforeach; ?>
</select>
like image 32
gmwraj Avatar answered Oct 09 '22 12:10

gmwraj


Since the l10n functions do not accept variables, translate_user_role() is required to translate the role names properly. Also, using wp_roles() rather than the global variable $wp_roles is the safer approach, for it first checks if the global is set and if not will set it and return it.

$roles = wp_roles()->get_names();

foreach( $roles as $role ) {
    echo translate_user_role( $role );
}
like image 37
Marc Wiest Avatar answered Oct 09 '22 11:10

Marc Wiest


Just an additional information. There's also a function wp_dropdown_roles() which gives you the roles as option html elements.

<select>
   <?php wp_dropdown_roles(); ?>
</select>

You can also set the default selected value by passing the role slug as a parameter.

<select>
   <?php wp_dropdown_roles( 'editor' ); ?>
</select>
like image 24
Chris Laconsay Avatar answered Oct 09 '22 11:10

Chris Laconsay