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:
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
function role_exists( $role ) { | |
if( ! empty( $role ) ) { | |
return $GLOBALS['wp_roles']->is_role( $role ); | |
} | |
return false; | |
} |
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
if( role_exists( 'editor' ) ) { | |
// The 'editor' role exists! | |
} |