Yogesh Chauhan's Blog

user_can vs current_user_can in WordPress

in WordPress on July 19, 2021

user_can

user_can function returns if a user (passed as an argument) has a specific capabilities (also passed as an argument).

Syntax


user_can($user, $capability, $meta_args )

Where $user is required as an user ID or object. $capability is also required as a string (capability name).

The $meta_args are optional and useful if you want to check if the capability is a meta capability.

The return value is boolean — true or false against your check.

edit_post and edit_user capabilities are meta capabilities.

Meta capabilities are used by the map_meta_cap() function to check if the user has any capabilities that are relating to the meta capabilities.

Examples


user_can( $user->ID, 'edit_posts' );
user_can( $user->ID, 'edit_post', $post->ID );
user_can( $user->ID, 'edit_post_meta', $post->ID, $meta_key );

current_user_can

current_user_can is similar to the user_can function but it’ll check against the current logged in user.

Syntax

The syntax omits the first argument from the user_can syntax.


user_can($capability, $meta_args )

The return value is boolean — true or false against your check same as user_can.

Examples


user_can( 'edit_posts' );
user_can( 'edit_post', $post->ID );
user_can( 'edit_post_meta', $post->ID, $meta_key );

Make sure to test before deploying since this function produces unexpected results sometimes.

Hide admin bar

You can hide admin bar using this code if the current logged in user is not admin or has not been granted any administrative access


if ( ! current_user_can( 'manage_options' ) ) {
    add_filter( 'show_admin_bar', '__return_false' );
}


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
A few HTML coding standards from WordPressHTMLAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to convert a function component into a class in React?ReactHow to display a student’s individual transcript in Colleague?Colleague3 Common Usability Mistakes In Web DesignUI/UXSolution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’Swift