When adding a new user role with add_role(), are there any capabilities attributed to the role (or allowed by the role) by default?

It is possible to create a role without defining any capabilities. There will simply be no capabilities set for this role in the database. However, you can explicitly deny capabilities by setting them to false upon creating the role.

$capabilities
(array) (Optional) List of capabilities, e.g. array( ‘edit_posts’ => true, ‘delete_posts’ => false );

I have seen examples of this, but I am left wondering why this would ever be necessary unless WordPress assumes that a newly created role has certain capabilities until otherwise excluded.

For example, are all roles assumed to have the read capability unless the capability is explicitly excluded? I can use get_role( $new_role )->capabilities; to get a list of capabilities which are explicitly set, but this does not answer my question about how WordPress handles new roles. If no capabilities are explicitly set for a new role then this will return empty.

Must I exclude all capabilities I don’t not want a role to have or does WordPress presume all capabilities to be false until they are set as true?

Edit: This question was inspired by an example on the developer site which sets a capability to false when a role is created. I can’t see why this would be necessary.

$result = add_role(
    'guest_author',
    __( 'Guest Author', 'testdomain' ),
    array(
        'read'         => true,  // true allows this capability
        'edit_posts'   => true,
        'delete_posts' => false, // Use false to explicitly deny
    )
);

3 Answers
3

I’ve found that the WordPress has_cap() function, which is relied on by functions like user_can() and current_user_can, explicitly returns false for empty capabilities.

Example: If a capability is passed as an argument using current_user_can(), this function will pass the capability to has_cap() and return the results:

    return call_user_func_array( array( $current_user, 'has_cap' ), $args

has_cap() will return false if the requested capability does not exist or the value is false:

foreach ( (array) $caps as $cap ) {
    if ( empty( $capabilities[ $cap ] ) )
        return false;
}

This is because the empty() function returns true in either case.

A variable is considered empty if it does not exist or if its value
equals FALSE.

Unless I am mistaken about how these functions work, then it appears safe to say that no default capabilities are attributed to a new role unless explicitly set to true. It is not necessary to explicitly deny a capability when creating a new role with add_role() and I can’t see any reason to do so. If a capability is not listed, the user will not have it.

Leave a Reply

Your email address will not be published. Required fields are marked *