This answer here is almost exactly what I'm after, but I'm just having trouble making it work for me.

Basically I've set a bunch of custom user roles using add_role() and register_activation_hook(). I then want to be able to restrict users to viewing certain content based on those user roles. They are not allowed to edit at all.

At this time I've just dropped the code from that answer into my functions.php and have edited it with my categories. So it looks like so:

add_filter('template_include', 'restict_by_category');

function check_user() {
    $user = wp_get_current_user();
    if ( ! $user->ID || in_array('subscriber', $user->roles) ) {
        // user is not logged or is a subscriber
        return false;
    return true;

function restict_by_category( $template ) {
    if ( ! is_main_query() ) return $template; // only affect main query.
        $allow = true;
        $private_categories = array('pilots', 'instructors');

        if ( is_single() ) {
            $cats = wp_get_object_terms( get_queried_object()->ID, 'category', array('fields' => 'slugs') ); // get the categories associated to the required post

            if ( array_intersect( $private_categories, $cats ) ) {
                // post has a reserved category, let's check user
                $allow = check_user();

        } elseif ( is_tax('category', $private_categories) ) {
            // the archive for one of private categories is required, let's check user
            $allow = check_user();

    // if allowed include the required template, otherwise include the 'not-allowed' one
    return $allow ? $template : get_template_directory() . '/not-allowed.php';

What I am expecting to happen with this, so far, is that if the user is not logged in, or is logged in as a subscriber, they will not be able to see posts that include 'pilots' or 'instructors' in their category lists. What is actually happening is that the 'pilots' and 'instructors' posts are visible to everyone.

The specific posts and categories in question have been created through the use of a knowledgebase plugin. So I'm wondering, could this be not working because my "categories" are actually custom taxonomies? If yes, how can I discover that for sure?

Or is there just something wrong with/missing from my code?

1 Answer 1


Turns out the issue with my category was that it was a custom taxonomy:

elseif ( is_tax('category', $private_categories) )

needed to be

elseif ( is_tax('wzkb_category', $private_categories) )

Super simple but might send someone down the correct path in future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.