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

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
How to make a Custom Login Page in WordPress?WordPress4 advanced ways to search ColleagueColleagueHTML canvas methodsHTMLEssential SQL Commands We Need to KnowSQL/MySQLAvoid using new Array() in JavaScriptJavaScriptWhat is an API?Miscellaneous