Created
March 18, 2024 19:22
-
-
Save robertdevore/7681fca7166fd7838eb3eea3fce79325 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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