Skip to content

Instantly share code, notes, and snippets.

@robertdevore
Created March 18, 2024 19:22
Show Gist options
  • Save robertdevore/7681fca7166fd7838eb3eea3fce79325 to your computer and use it in GitHub Desktop.
Save robertdevore/7681fca7166fd7838eb3eea3fce79325 to your computer and use it in GitHub Desktop.
<?php
/**
* Checks if a particular user has one or more roles.
*
* Returns true on first matching role. Returns false if no roles match.
*
* @param array|string $roles - Role name (or array of names).
* @param int $user_id - (Optional) The ID of a user. Defaults to the current user.
*
* @uses get_userdata()
* @uses wp_get_current_user()
*
* @return bool
*/
function check_user_roles( $roles, $user_id = null ) {
// Default user ID.
$user = wp_get_current_user();
// Set user ID.
if ( is_numeric( $user_id ) ) {
$user = get_userdata( $user_id );
}
// Bail early?
if ( empty( $user ) ) {
return false;
}
// Get user roles.
$user_roles = (array) $user->roles;
// Loop through user roles.
foreach ( (array) $roles as $role ) {
if ( in_array( $role, $user_roles ) ) {
// Role found.
return true;
}
}
// Role(s) not found.
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment