Opened 3 years ago
Closed 3 years ago
#14602 closed enhancement (fixed)
Create user_can, refactor current_user_can, author_can, current_user_can_for_blog
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | 3.1 |
| Component: | Role/Capability | Version: | 3.0.1 |
| Severity: | normal | Keywords: | has-patch needs-testing |
| Cc: |
Description
Currently we have no function to pass a user ID and a capability/rolewhich will return whether the user can perform that role or has that capability. Further, the functions current_user_can, author_can, and current_user_can_for_blog have some code duplication.
I suggest adding a new function user_can, which accepts any user_ID or a user object and a capability, and returns a boolean. The other *_can* functions can then be refactored to use the new function.
See attached patch.
Attachments (1)
Change History (8)
comment:1
simonwheatley — 3 years ago
- Component changed from Users to Role/Capability
- Milestone changed from Awaiting Review to 3.1
Looking good. +1
But I think you should drop the * @author Simon Wheatley from the docblock.
comment:4
in reply to:
↑ 2
;
follow-up:
↓ 5
simonwheatley — 3 years ago
Replying to scribu:
Looking good. +1
Should the user_can function be using get_userdata rather than instantiating a new WP_User object every time, so it takes advantage of the cache?
Replying to simonwheatley:
Replying to scribu:
Looking good. +1
Should the user_can function be using get_userdata rather than instantiating a new WP_User object every time, so it takes advantage of the cache?
No, because WP_User calls get_userdata() internally.
I think each of these functions still need to get the args, slice, merge, and call_user_func_array() so that the extra args aren't dropped. After doing all that has_cap should be called directly rather than going through user_can() and doing the same thing again.
comment:7
automattor — 3 years ago
- Resolution set to fixed
- Status changed from new to closed

Looking at the current patch I wonder whether the is_int check in the first line of the new user_can function ought to be more like this:
function user_can( $user, $capability ) { if ( ! is_object( $user ) ) $user = new WP_User( (int) $user ); if ( ! $user || ! $user->ID ) return false; $args = array_slice( func_get_args(), 2 ); $args = array_merge( array( $capability ), $args ); return call_user_func_array( array( &$user, 'has_cap' ), $args ); }