WordPress: Check if user role exists

As part of a recent Sensei update we added some custom capabilities to the editor role, but we discovered that some people have deleted that role from the database as a way of cleaning up unused data on their sites. This meant that our add_cap() calls were causing fatal errors for these sites.

While that is admittedly a fringe case, it’s useful to know how to check if a role exists in the database before you go about manipulating it. It’s actually really easy to do, but WordPress doesn’t have a handy role_exists() function or something similar, so it requires a small amount of custom coding.

Here’s how we added a function like this and solved the problem for ourselves along with the basic usage:


function role_exists( $role ) {
if( ! empty( $role ) ) {
return $GLOBALS['wp_roles']->is_role( $role );
}
return false;
}

view raw

function.php

hosted with ❤ by GitHub


if( role_exists( 'editor' ) ) {
// The 'editor' role exists!
}

view raw

usage.php

hosted with ❤ by GitHub

Leave a Reply