Categories
code WordPress

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:

<?php
// figure out which user role the current user has 
$user_meta = wp_get_current_user();
$user_roles = $user_meta->roles ;

// query the $user_roles array: 
// only users of 2 given roles are allowed to see the content

if (( in_array('role_1', $user_roles ) ) || ( in_array('role_2', $user_roles ) ) ){
  // display content or do something else

 } else {
	echo 'Sorry, this content is restricted.';

} //end of if to control access to page content
?>

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:

<?php
// figure out which user role the current user has 
$user_meta = wp_get_current_user();
$user_roles = $user_meta->roles ;

// query the $user_roles array: only users of a certain role are allowed to see the content
if ( !in_array('role_1', $user_roles ) ){

  echo 'Sorry, this content is restricted.';

} else {
	//display content or do something else

} //end of if to control access to page content
?>