WordPress User Role Pages
November 21, 2014


Recently, I was creating a site in WordPress where there would be a created user role and they had to have access to certain pages on the site but not subscribers. However – they had the same capabilities as the Subscriber role so I couldn’t use the normal current_user_can( … ) function to create the private pages. I went out on an epic quest (maybe it wasn’t really that epic…) across the WordPress forums to find out how to check a user’s current role by name, and I eventually found a solution.

First thing’s first though, we need to create a new user role. I’ve already gone into how to do this in my WordPress User Roles post, so check that out if you need to. Below is the code I used as an example:

Simply add this code to your functions.php and then the new user role will be created. This is the quickest (and dirtiest) way to get this done. In my WordPress User Roles post I go over how to add this code to a plugin so it only runs once when the plugin is activated. Check it out if you want to do it that way.

You can remove the above code from your functions.php file once the user is created.

The first thing to get everything working is to make a function that will discover the current user’s role name. This can be achieved with the following function (thanks to WordPress forum user caugb for this one):

Once you have this function, you either need to add it to your functions.php file or to the template file you are working with. I just added it to the template when I did it since I was going fast and dirty but if you plan on using it on more than one template I would add it to your functions.php file.

Now its time to start looking at the actual template. What we need to do is get the current user’s role with our function, check if the user is logged in and if their current role is set to our Sample User Role that we created above. If they are logged in and have the right role then everything is good, we load the content. If not, then we redirect them to the home page. The code can be found below:

Make sure you add the code to display content @ line 18! This will be theme specific.

If you want to make it so Administrators of the site also have access to the site, just change the 16th line to read:

For the sake of the extremely lazy people out there, the entire template file with the addition of Administrator access can be copied below if you want. The only change is line 16 which I changed to include the Administrator user role as described above.

Again, make sure you add the code to display content @ line 18! This will be theme specific.

And that’s all there is to it. If you are not either an Administrator or a Sample User Role then you will not have access to that page.

As always thank you for reading and please share it around as much as you can! Please feel free to put any suggestions or ideas for future tutorials in the comments section below.