How to Use current_user_can in WordPress for Permission Checks
Use
current_user_can in WordPress to check if the logged-in user has a specific capability or role before allowing actions. It returns true if the user has the capability, otherwise false. This helps control access to admin features or content.Syntax
The current_user_can function takes one required parameter: a capability string that represents the permission you want to check. It returns a boolean value indicating if the current user has that capability.
- capability: A string like
'edit_posts','manage_options', or a custom capability.
php
current_user_can( string $capability ) : bool
Example
This example shows how to check if the current user can edit posts before displaying an edit link. If the user lacks permission, the link won't show.
php
<?php if ( current_user_can( 'edit_posts' ) ) { echo '<a href="/wp-admin/post.php?post=123&action=edit">Edit this post</a>'; } else { echo 'You do not have permission to edit posts.'; } ?>
Output
If user can edit posts: <a href="/wp-admin/post.php?post=123&action=edit">Edit this post</a>
If not: You do not have permission to edit posts.
Common Pitfalls
Common mistakes include:
- Using
current_user_canoutside of a logged-in context, which always returns false. - Checking roles instead of capabilities;
current_user_canchecks capabilities, not roles. - Passing incorrect capability names or typos.
- Not considering that some capabilities are mapped to multiple roles.
Always verify the capability name and ensure the user is logged in before checking.
php
<?php // Wrong: Checking role name instead of capability if ( current_user_can( 'administrator' ) ) { echo 'You are an admin'; } // Right: Check a capability that admins have if ( current_user_can( 'manage_options' ) ) { echo 'You have admin capabilities'; } ?>
Quick Reference
| Capability | Description | Common Roles |
|---|---|---|
| edit_posts | Allows editing posts | Author, Editor, Administrator |
| publish_posts | Allows publishing posts | Author, Editor, Administrator |
| manage_options | Allows managing site options | Administrator |
| edit_users | Allows editing users | Administrator |
| delete_posts | Allows deleting posts | Author, Editor, Administrator |
Key Takeaways
Use current_user_can to check user capabilities, not roles.
Always pass a valid capability string to current_user_can.
current_user_can returns false if no user is logged in.
Use capability checks to control access to admin features or content.
Avoid checking roles directly; rely on capabilities for permission logic.