How to use the current_user_can function in WordPress
Last updated:
This article explains how to use the current_user_can function in WordPress. It also introduces the parameters, return value, and examples of usage.
What is the current_user_can function?
Returns whether the current user has the specified capability or not.
Structure
The current_user_can function is written as follows.
current_user_can( $capability, $args )
Parameters
2 parameters can be specified in the current_user_can function.
Parameter name | Description |
---|---|
$capability (Required) | Capability name |
$args | Additional Parameters |
$capability
Specify the capability name. Required.
It is also possible to specify a role (admin/editor/contributor/contributor/subscriber) for $capability, but this may return unintended results.
$args
Specify additional parameters, such as $post_id. It is optional.
Return
Returns true if the current user has the specified capability, false if not.
How to use the current_user_can function
Explains how to use the current_user_can function to check if the current user has article editing capability.
Specifying Capability
edit_posts is a parameter of current_user_can function that represents the capability to edit an article.
It’s a string, so use single quotes to enclose the parameters.
current_user_can( 'edit_posts' )
Specified in the conditional expression of the IF statement
Check to see if the current user is authorized by specifying the current_user_can function as a conditional expression in the IF statement.
if( current_user_can( 'edit_posts' ) ){
//Processing for users with article editing rights
}
Example of using the current_user_can function
An example of the use of the current_user_can function is shown below.
How to check if the current user is Administrator in WordPress
Supported Versions
WordPress 2.0.0 or later
Source code
The current_user_can function is defined in “wp-includes/capabilities.php”.