dots Created with Sketch.
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' );
}

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
FETCH clause in PostgreSQLPostgresWordPress: How to get ACF field values from another post?WordPressIs there a difference between SCSS and Sass?SCSSHow destructuring works in React?ReactWordPress get_posts ExamplesWordPressHow to check if checkbox is checked or not using JavaScript?JavaScript