Make WordPress Core

Opened 2 months ago

Last modified 2 months ago

#65508 new feature request

Introduce wp_get_user_roles() helper function

Reported by: salmanshafiq8630 Owned by:
Priority: normal Milestone: Awaiting Review
Component: Users Version: 7.0
Severity: normal Keywords: 2nd-opinion has-patch
Cc: Focuses:

Description

## Summary

Introduce a new helper function, wp_get_user_roles(), to provide a public API for retrieving the roles assigned to a user.

Currently, developers need to retrieve a WP_User object and access its public roles property directly:

`php
$user = get_userdata( $user_id );
$roles = $user ? $user->roles : array();
`

This requires knowledge of the internal structure of the WP_User object and exposes a public property instead of using a dedicated API.

## Proposed solution

Add a new helper function to wp-includes/user.php:

`php
/

  • Retrieves the roles assigned to a user. *
  • @since 7.1 *
  • @param int $user_id User ID.
  • @return string[] Array of role slugs. Returns an empty array if the user does not exist or has no assigned roles. */

function wp_get_user_roles( $user_id ) {

$user = get_userdata( $user_id );

if ( ! $user instanceof WP_User
empty( $user->roles ) ) {

return array();

}

return $user->roles;

}
`

## Benefits

  • Provides a dedicated public API for retrieving user roles.
  • Avoids direct access to the WP_User::$roles property.
  • Improves readability and consistency with existing user helper functions such as wp_get_current_user().
  • Simplifies a common pattern used by plugins and themes.

## Unit tests

Tests should cover:

  • Valid user with a single role.
  • Valid user with multiple roles.
  • Invalid user ID.
  • User with no assigned roles.

Change History (1)

Note: See TracTickets for help on using tickets.