Using WordPress ‘current_user_can()’ PHP function

The current_user_can() WordPress PHP function is used to determine if the current user has a specific capability. It can also accept an object’s ID for checking meta capabilities such as ‘edit_post’ and ‘edit_user’. A meta capability maps to primitive capabilities like ‘edit_posts’ and ‘edit_others_posts’.

Usage

Here’s how you would typically use the current_user_can() function:

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

Parameters

  • $capability (string) – The name of the capability you want to check.
  • $args (mixed) – Optional additional parameters, generally starting with an object ID.

More information

See WordPress Developer Resources: current_user_can()

Please note that the current_user_can() function will always return true if the current user is a super admin, unless explicitly denied. It’s discouraged to check against specific roles instead of capabilities, as it may yield unreliable results.

Examples

Checking Roles

Here’s a way to check if the current user has one of several roles:

$user = wp_get_current_user();
$allowed_roles = array( 'editor', 'administrator', 'author' );

if ( array_intersect( $allowed_roles, $user->roles ) ) {
  // Code for allowed roles
}

Admin Bar Visibility

To hide the admin bar for users who can’t edit posts:

if ( !current_user_can( 'edit_posts' ) ) {
  show_admin_bar( false );
}

Restricting Non-Admin Access

To hide the admin bar from users without admin access:

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

Checking Post Edit Access

To check if a user can edit a specific post by ID:

if ( ! current_user_can( 'edit_post', $post_id ) ) {
  return false;
}

Capability Denial for Super Admins

Explicitly denying a capability for super admins:

add_filter( 'map_meta_cap', function( $caps, $cap ) {
  if ( 'some_capability' === $cap ) {
    $caps = array('do_not_allow');
  }
  return $caps;
}, 10, 2 );

In this example, the map_meta_cap filter is used to explicitly deny ‘some_capability’ for super admins.