1

I want to know if it is good practice to use:

if ( current_user_can( 'edit_user', $user_id ) ) {
    // do something
}

because in Wordpress documentation a did not see this capability

  • 1
    Can you elaborate on good practice, good practice for what? What are you trying to use this for? – Tom J Nowell Nov 19 '14 at 15:16
  • @tom-j-nowell I saw this in user-edit.php if ( !current_user_can('edit_user', $user_id) ) wp_die(__('You do not have permission to edit this user.')); And I want to know if I can use it in other parts. – user1147145 Nov 19 '14 at 15:20
3

Yes it can be good practice to check if a user is capable of doing something before doing something related in code.

For example, don't save a custom post type if the user doesn't have the capabilities needed to do it, or don't show certain things to users who don't have the manage_options capability ( super admins and admins normally ).

Bad practice in this case would be assuming the user has the necessary role to do these things and doing them anyway. This doesn't mean you should fill your code with checks for current_user_can everywhere though, in many places ( such as registering admin menus ), the check is performed by WP Core itself

  • I want to use update_user_meta() in backend part on parse_query filter , and update the usermeta in dependency of some $_GET['tmp'] parameter – user1147145 Nov 19 '14 at 15:33
  • You should probably be using POST rather than GET for that – Tom J Nowell Nov 20 '14 at 1:11
0

All it's doing is checking the current user's capabilities against the user-in-question, and returning a boolean value. I don't think 'good practice' can be applied to this scenario without a more complete picture of what you are trying to do. (what code will be executed if the bool is true?)

That being said, I see no problem with simply using this check, and it certainly isn't 'bad practice'. So, go for it.

0
current_user_can( 'edit_user', $user_id )

This term performs a check on the »meta capability« edit_user. By default, it maps to the capability edit_users, which is a typical capability for the admin role. Furthermore it compares the ID of the current user and the user ID given as parameter. If they match, the statement becomes TRUE, because each user should have the possibility to edit its own profile.

These evaluations can be affected by the map_meta_cap filter. Thereby a plugin could grant privileges to a user (or a group of users) over a subset of all users. Thinking about a »moderator« role or something like that.

Anytime your code changes some user-related settings or user-data, you should perform this check, if the current user has the privilege to edit this users data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.