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
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>
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>
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 );
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With