Restricting Content to User Roles

Sometimes, content is aimed at certain people or user groups only. Sometimes it contains data you need to make sure it’s not spread all over our beautiful World Wide Web. And in some of these cases, the way to do it is not to just add a plugin and click a button. 😉

So my task was to not only hide content from plain sight but it should be accessible  to two user groups only.

First I needed to figure out where the information about user roles is stored. It’s in the WP_User object. You can access information stored there via the function wp_get_current_user.

You need to get the array containing the user roles, then you are able to check if the user that just wants to get access to your content has the appropriate role:

This worked for me nicely.

If I’d only had one role to restrict to I’d chosen to do it the other way around, because I found it easier to comprehend, like so: