WordPress Functions

WordPress: current_user_can Function

24 October 2023

Often arises a situation where you need to very precisely control what different users can and cannot do. For instance, in a custom Wordpress site where users can upload their own header image for their personal pages. But how do you ensure they only edit their own custom header image page and not touch anyone else’s? Or what if you want to display or hide certain default post meta boxes depending on the user’s permissions? This is where the function `current_user_can` needs to be used.

This function checks whether the current user has the specified capability or not, be it editing a post, deleting posts, or anything that would require a degree of authorization control. Now, let’s say an object ID was passed, in addition with a certain meta capability. The function then also checks if the current user has the given meta capability for that specified object. Whether it’s for a simple task like retrieving menu meta boxes, or more complex ones like editing user link or post meta data, this function makes sure only the appropriate users have the right to take action. Understanding it properly can be a difference between a functional Wordpress site and a security nightmare.

Syntax

current_user_can( $capability, ...$args )

Parameters

  • $capability (string): The name of the capability being checked.
  • …$args (mixed): Optional further parameters, typically starting with an object ID.

Return Value

  • bool: Whether the current user has the given capability. If $capability is a meta cap and $object_id is passed, it checks whether the current user has the given meta capability for the given object.

How it Works

<?php
/**
* Returns whether the current user has the specified capability.
*
* This function also accepts an ID of an object to check against if the capability is a meta capability. Meta
* capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to
* map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`.
*
* Example usage:
*
* current_user_can( 'edit_posts' );
* current_user_can( 'edit_post', $post->ID );
* current_user_can( 'edit_post_meta', $post->ID, $meta_key );
*
* While checking against particular roles in place of a capability is supported
* in part, this practice is discouraged as it may produce unreliable results.
*
* Note: Will always return true if the current user is a super admin, unless specifically denied.
*
* @since 2.0.0
* @since 5.3.0 Formalized the existing and already documented `...$args` parameter
* by adding it to the function signature.
* @since 5.8.0 Converted to wrapper for the user_can() function.
*
* @see WP_User::has_cap()
* @see map_meta_cap()
*
* @param string $capability Capability name.
* @param mixed ...$args Optional further parameters, typically starting with an object ID.
* @return bool Whether the current user has the given capability. If `$capability` is a meta cap and `$object_id` is
* passed, whether the current user has the given meta capability for the given object.
*/
function current_user_can( $capability, ...$args ) {
return user_can( wp_get_current_user(), $capability, ...$args );
}

The current_user_can() function calls another function called user_can(), passing in the current user object obtained from wp_get_current_user() and the specified capability along with any additional arguments provided.

The purpose of this function is to simplify checking capabilities by wrapping it in a more intuitive API. Instead of directly calling user_can() with the current user object every time, developers can use current_user_can() for convenience.

This function follows a pattern commonly used in WordPress where helper functions are created to provide more readable and simpler alternatives to existing functions. In this case, rather than calling user_can(), developers can call current_user_can() which performs an identical operation behind-the-scenes.

Usage

Inside a Plugin

Let’s say you are developing a custom WordPress plugin that allows users with the specified capability to access a special feature. You can use the current_user_can function to check if the current user has the required capability before granting them access.

<?php
/**
* Check if the current user has access to the special feature.
*/
function check_special_feature_access()
{
// Set the required capability for accessing the special feature
$capability = "manage_special_feature";
// Check if the current user has the specified capability
if (current_user_can($capability)) {
// Grant access to the special feature
// Your code goes here...
} else {
// Display an error message or redirect to another page
wp_die("You do not have permission to access this feature.");
}
}

In this example:

  • You define the required capability for accessing the special feature as ‘manage_special_feature’.
  • The current_user_can function is used to check if the current user has the specified capability.
  • If the user has the capability, you can proceed with your custom code logic for implementing the special feature.
  • If the user does not have the capability, you can display an error message or redirect them elsewhere.

To make this functionality available within your plugin, you can hook it into an appropriate action or filter. For example:

<?php
// Hook into an admin menu action
add_action('admin_menu', 'check_special_feature_access');

Inside a Theme

Imagine you are working on a custom WordPress theme that includes a restricted area where only users with specific capabilities can view and modify certain settings. You can utilize current_user_can in combination with conditional statements to restrict access based on user capabilities.

<?php
/**
* Display theme options in WordPress Customizer.
*/
function customize_theme_options()
{
// Define the capability required to access the theme options
$capability = "edit_theme_options";
// Check if the current user has the specified capability
if (current_user_can($capability)) {
// Show the theme options in Customizer
// Your code goes here...
} else {
// Display a message indicating that the user does not have permission
echo 'Sorry, only users with the necessary capabilities can access this page.';
}
}

In this example:

  • You set ‘edit_theme_options’ as the required capability for accessing theme options.
  • The current_user_can function is used to check if the current user has the specified capability.
  • If the user has the capability, you can display and modify theme options using WordPress Customizer or perform other actions.
  • If the user does not have the capability, you can display a message stating that they do not have permission to access the page.

To incorporate this functionality into your theme, you can use appropriate hooks such as admin_init, customize_register, or any customized action hooks specific to your theme implementation. For instance:

<?php
// Hook into customize_register action for displaying theme options in Customizer
add_action('customize_register', 'customize_theme_options');
Leave a Reply

Your email address will not be published. Required fields are marked *

Array

Some of Our Clients

Join clients who enjoy 96% satisfaction

Schedule a Free Strategy Call with a WordPress Expert