Last active
May 30, 2020 15:39
-
-
Save hlashbrooke/8f901da7c6f0d107add7 to your computer and use it in GitHub Desktop.
WordPress: Check if user role exists
This file contains hidden or 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
function role_exists( $role ) { | |
if( ! empty( $role ) ) { | |
return $GLOBALS['wp_roles']->is_role( $role ); | |
} | |
return false; | |
} |
This file contains hidden or 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
if( role_exists( 'editor' ) ) { | |
// The 'editor' role exists! | |
} |
@widoz +1
Rather than get_role(), which returns the WP_Role
object, if you're really only interested in knowing whether a role exists (for example, if you want to determine whether to remove_role()
or something), how about wp_roles()->is_role( 'role-name' );
? Maybe a tiny bit more efficient than get_role()
and a bit more future-proof than digging directly into the global $wp_roles
.
+1 to @TomAuger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do not use the simple built in wp function get_role that returns a WP_Role object on success, null on failure ?
https://codex.wordpress.org/Function_Reference/get_role