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:

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s