WP_User::get_role_caps(): bool[]

Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities.

Description

All of the capabilities of the user’s roles are merged with the user’s individual capabilities. This means that the user can be denied specific capabilities that their role might have, but the user is specifically denied.

Return

bool[] Array of key/value pairs where keys represent a capability name and boolean values represent whether the user has that capability.

Source

public function get_role_caps() {
	$switch_site = false;
	if ( is_multisite() && get_current_blog_id() !== $this->site_id ) {
		$switch_site = true;

		switch_to_blog( $this->site_id );
	}

	$wp_roles = wp_roles();

	// Filter out caps that are not role names and assign to $this->roles.
	if ( is_array( $this->caps ) ) {
		$this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) );
	}

	// Build $allcaps from role caps, overlay user's $caps.
	$this->allcaps = array();
	foreach ( (array) $this->roles as $role ) {
		$the_role      = $wp_roles->get_role( $role );
		$this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities );
	}
	$this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps );

	if ( $switch_site ) {
		restore_current_blog();
	}

	return $this->allcaps;
}

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Code sample

    // Define user ID
    $user_id = 1;
    
    // Get User
    $user = new WP_User( $user_id );
    
    // Get all user capabilities
    $user_roles = $user->get_role_caps();
    
    // Check if user has permission
    if ($user_roles['manage_options']) {
        // Do stuff
    }

    Response sample

    array(10) {
        ["switch_themes"] => bool(false)
        ["edit_themes"] => bool(true)
        ["activate_plugins"] => bool(true)
        ["edit_plugins"] => bool(true)
        ["edit_users"] => bool(true)
        ["edit_files"] => bool(false)
        ["manage_options"] => bool(true)
        ["moderate_comments"] => bool(true)
        ["manage_categories"] => bool(true)
        ["manage_links"] => bool(false)
    }
  2. Skip to note 4 content

    In your plugin you can define to filter certain role and cap to do certain staff.

    const WPDOCS_ALLOWED_ROLE_FILE_CREATIONS = array( 'administrator', 'edit_plugins', 'manage_options' );

    So Filter When Necessary

    $allowed = self::WPDOCS_ALLOWED_ROLE_FILE_CREATIONS;
    $roles_caps = wp_get_current_user()->get_role_caps();
    foreach ( $roles_caps as $role => $val ) {
    	if ( in_array( $role, $allowed ) ) {
    		if ( $val ) {
    			// user permitted here
    		}
    	}
    }

You must log in before being able to contribute a note or feedback.