Get current user capabilities

admin2025-05-31  0

I am trying to get user capabilities.

$user = wp_get_current_user();

$user_roles = $user->roles;

$allowed_capability = get_role( $user_roles[0] )->capabilities;


var_dump($allowed_capability);

array(10) {
 ["upload_files"]=>
 bool(true)
 ["edit_posts"]=>
 bool(true)
 ["edit_published_posts"]=>
 bool(true)
 ["publish_posts"]=>
  bool(true)
  ["read"]=>
  bool(true)
 ["level_2"]=>
 bool(true)
 ["level_1"]=>
 bool(true)
 ["level_0"]=>
 bool(true)
 ["delete_posts"]=>
 bool(true)
 ["delete_published_posts"]=>
 bool(true)
}

when I try to get first capability:

$user_cap = $allowed_capability[0];

I get:

Notice: Undefined offset: 0 

How do I get "upload_files" for example?

I am trying to get user capabilities.

$user = wp_get_current_user();

$user_roles = $user->roles;

$allowed_capability = get_role( $user_roles[0] )->capabilities;


var_dump($allowed_capability);

array(10) {
 ["upload_files"]=>
 bool(true)
 ["edit_posts"]=>
 bool(true)
 ["edit_published_posts"]=>
 bool(true)
 ["publish_posts"]=>
  bool(true)
  ["read"]=>
  bool(true)
 ["level_2"]=>
 bool(true)
 ["level_1"]=>
 bool(true)
 ["level_0"]=>
 bool(true)
 ["delete_posts"]=>
 bool(true)
 ["delete_published_posts"]=>
 bool(true)
}

when I try to get first capability:

$user_cap = $allowed_capability[0];

I get:

Notice: Undefined offset: 0 

How do I get "upload_files" for example?

Share Improve this question asked May 13 at 16:27 ToniqToniq 4476 silver badges15 bronze badges 2
  • $first = reset( $allowed_capability ); However, keep in mind that an associative array is essentially a dictionary that has no "order". So you might get a different value for the same user at a different time. We could help you better, if you'd explain you use case. – fuxia Commented May 13 at 16:33
  • 2 are you trying to list capabilities or test for a specific one? The approach of testing via [] is very unusual and ignores meta capabilities and filters. Have you looked at the current_user_can function? – Tom J Nowell Commented May 13 at 16:51
Add a comment  | 

1 Answer 1

Reset to default 0

The array you are trying to access is associative so you can't get the data like that...

You access it via the name like so:

$user_cap = $allowed_capability['upload_files'];
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748631085a313656.html

最新回复(0)