danyo
danyo

Reputation: 5846

wordpress list user roles

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

Upvotes: 8

Views: 23276

Answers (6)

Nishad Up
Nishad Up

Reputation: 3615

If you are looking for Dropdown options, use WordPress native function wp_dropdown_roles This will give Translated user roles

Here is the code example

<select name="default_role" id="default_role">
    <?php wp_dropdown_roles( get_option( 'default_role' ) ); ?>
</select>

Upvotes: 0

Abdullah Mahi
Abdullah Mahi

Reputation: 152

you would like to display a select list of available WordPress role names.

$roles_obj = new WP_Roles();
$roles_names_array = $roles_obj->get_names();
echo '<select name="role">';
foreach ($roles_names_array as $role_name) {
    echo '<option>'.$role_name.'</option>';
}
echo '</select>';

Upvotes: 0

Marc Wiest
Marc Wiest

Reputation: 359

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 );
}

Upvotes: 5

Chris Laconsay
Chris Laconsay

Reputation: 412

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>

Upvotes: 3

gmwraj
gmwraj

Reputation: 121

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>

Upvotes: 5

Marty
Marty

Reputation: 4657

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>

Upvotes: 12

Related Questions