Wordpress User Roles

I am working on a wordpress project and delving into roles, etc.

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

<?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 removed from the array and into a simply unordered list. How can i achieve this?

Thanks Dan

+4
source share
4 answers

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

 <ul> <?php foreach($roles as $role) { ?> <li><?php echo $role;?></li> <?php }//end foreach ?> </ul> 
+7
source

Here is the code for creating a Wordpress user role dropdown

 <?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> 
+2
source

Since l10n functions do not accept variables , translate_user_role() must correctly translate the role names. In addition, using wp_roles() , and not the global variable $wp_roles , is a saving method for it, first it checks if the global one is set, and if not, sets it and returns it.

 $roles = wp_roles()->get_names(); foreach( $roles as $role ) { echo translate_user_role( $role ); } 
+2
source

Just extra info. There is also a wp_dropdown_roles () function that provides you roles as elements of html options.

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

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

 <select> <?php wp_dropdown_roles( 'editor' ); ?> </select> 
0
source

Source: https://habr.com/ru/post/1443272/


All Articles