aswiss
aswiss

Reputation: 35

current_user_can with custom role and capanbility always false

I've created a custom role "Expert" and added a custom capability to this role: "manage_zoom_meetings".

If I try to check if the current user has the capability, the function current_user_can('manage_zoom_meetings') returns false.

I've tested this code to check if the role is maybe not existing for the function current_user_can.

add_filter( 'user_has_cap', function ( $allcaps, $caps, $args, $user ) {
   wp_die( var_export( get_role( 'expert' )->capabilities, true ) );
   return $allcaps;
}, PHP_INT_MAX, 4 );

The output looks like this:

array ( 'level_0' => true, 'manage_zoom_meetings' => true, 'read' => true, )

I don't understand what is wrong here.

The problem is, that I'm not able to add this capability to an admin menu item (add_menu_page()) or to a custom post type.

Upvotes: 0

Views: 764

Answers (1)

joshmoto
joshmoto

Reputation: 5088

This is how I add custom roles and custom caps via function.php using add action init...

// add the expert role and capabilities on init
add_action('init', 'expert_role');
add_action('init', 'expert_role_caps', 11);

/**
 * create expert role
 * @return void
 */
function expert_role() {

    // add role function
    add_role(
        'expert',
        'Expert',
        [
            'read' => true
        ]
    );

}

/**
 * expert role meta capabilities vars
 * @var $expert_caps array
 */
$expert_caps = [
    'level_0',
    'manage_zoom_meetings'
];

/**
 * assign expert role capabilities
 * @param $expert_caps array
 * @return void
 */
function expert_role_caps($expert_caps) {

    // gets the expert role object
    $role = get_role('expert');

    // add a custom capability
    foreach ($expert_caps as $cap) {
        $role->add_cap($cap, true);
    }

}

Doing this should in theory make the below code return true when used anywhere on your site if their current user role is expert or if the current user has this capability...

var_dump(current_user_can('manage_zoom_meetings'));

Hope this helps :-)

Upvotes: 0

Related Questions