Do not display posts when user has no access

1 Reply ·

  1. We are building a restricted documents section within my site. The Members plugin works fine and does not give access to restricted documents unless the user has the appropriate role(s).

    However, when I display a page with posts or the result of a search, the titles of restricted posts appear and the user with no access begin wondering why they have no access to those.

    I need to find a way to avoid displaying any detail about restricted posts (or another type of content) when users with no access to those are browsing the website.

    Can you help me please?

    Thanks.

  2. Justin Tadlock

    This may take a little trial and error. Try the below code in your theme’s functions.php.

    add_action( 'pre_get_posts', 'my_pre_get_posts' );
    
    function my_pre_get_posts( $query ) {
    
        if ( is_admin() ) {
            return;
        }
    
        if ( is_user_logged_in() ) {
    
            $user = new WP_User( get_current_user_id() );
    
            $meta_query = array(
                'relation' => 'OR',
                array(
                    'key'    => '_members_access_role',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key'    => '_members_access_role',
                    'value'   => (array) $user->roles,
                    'compare' => 'IN'
                )
            );
    
        } else {
    
            $meta_query = array(
                array(
                    'key'    => '_members_access_role',
                    'compare' => 'NOT EXISTS'
                )
            );
        }
    
        $query->set( 'meta_query', $meta_query );
    }
    

    If this seems to be showing the opposite of what you want, change this line:

    'compare' => 'IN'
    

    To:

    'compare' => 'NOT IN'