Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Check if user role exists
function role_exists( $role ) {
if( ! empty( $role ) ) {
return $GLOBALS['wp_roles']->is_role( $role );
}
return false;
}
if( role_exists( 'editor' ) ) {
// The 'editor' role exists!
}
@widoz

This comment has been minimized.

Copy link

@widoz widoz commented May 21, 2015

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

@namenyi

This comment has been minimized.

Copy link

@namenyi namenyi commented Jul 3, 2015

@widoz +1

@TomAuger

This comment has been minimized.

Copy link

@TomAuger TomAuger commented Jan 10, 2017

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.

@0xcrypto

This comment has been minimized.

Copy link

@0xcrypto 0xcrypto commented Aug 12, 2017

+1 to @TomAuger

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment