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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Clean Form Input With These PHP Functions Before Inserting into DatabasePHPHow to add a scroll back to top button using JavaScript and CSS?CSSStyling Lists with CSSCSSHow to install Gulp with WordPress?WordPressHow to create a sidebar using pure CSS?CSSHow to create a simple text and image slider using CSS and JavaScript?CSS