How to restrict WordPress content by user role

posted on by - 1053 views

In this post we will learn how to restrict WordPress content by user role. There are two ways to do that: the first and easier one is a WordPress core functionality, that allows us to make content private and only visible to users with the right access level (Editors and Administrators); the second one is more flexible but a little more complex, because it involves some coding. Let’s see them in detail.

How to make WordPress content private (backend)

Let’s say we’re working on a post, a page or some other custom post type, and we want to make that item private. We can do that with the Publish options we can find on the top right of our page. We just have to set to Private the Visibility option: this way, only Editors and Administrator will be able to access that content. For everyone else it will return a 404 error page.

See the image below.

As you can see from the image, you can also set an item password protected.

How to restrict WordPress content by user role (coding)

If you’re familiar with some PHP code, you can use it to restrict whatever part of your website, just by adding some code in your theme files. Let’s say, for example, that we want to show a system error message only to administrators, so that our visitor wouldn’t be bothered with useless informations.

To do that, we can use a WordPress function called current_user_can(), which accepts capabilities (eg.: edit_posts) or user roles (eg.: administrator). Please, check this page for further informations.

So, we can do something like this:

if( current_user_can( 'administrator' ) ){
    echo "Error message";

This way, only administrators will see the error message. Of course, and this is just PHP logic, we can also show that error message to everyone but administrators:

if( !current_user_can( 'administrator' ) ){
    echo "Error message";

Quite easy, huh?

Of course, this was just an example: you can use that function to manage the visibility of every kind of content written in your theme files.