Is it possible to choose specific categories that will only be displayed to logged in members?

I tried to find a plugin or a PHP solution that does that but could not find anything that was still relevant.

2 Answers
2

Yes :).

The following will effect all queries for posts on the front-end including ‘secondary loops’ (e.g. post lists on the side) but it won’t effect custom post types. So this may not be exactly what you’re after, but the principle is the same:

add_action('pre_get_posts','wpse72569_maybe_filter_out_category');

function wpse72569_maybe_filter_out_category( $query ){

     //Don't touch the admin
     if( is_admin() )
         return;

     //Leave logged in users alone
     if( is_user_logged_in() )
         return;

     //Only effect 'post' queries
     $post_types = $query->get('post_type');
     if( !empty($post_types) && 'post' != $post_types )
         return;

     //Get current tax query
     $tax_query = $query->get('tax_query');

     //Return only posts which are not in category with ID 1
     $tax_query[] = array(
        'taxonomy' => 'category',
        'field' => 'id',
        'terms' => array( 1 ),
        'operator' => 'NOT IN'
          );

     //If this is 'OR', then our tax query above might be ignored.
     $tax_query['relation'] = 'AND';

     $query->set('tax_query',$tax_query);

}

Leave a Reply

Your email address will not be published. Required fields are marked *