• Resolved Kim Soler

    (@kimso)


    Hi,
    There’s some way to hide the posts from archive pages if the user don’t have permission to read the post?
    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author Caseproof LLC

    (@caseproof)

    Hi Kim,

    Members plugin doesn’t have such a feature out of the box. You’d likely need to modify the loop to check each post using the members_can_current_user_view_post( $post_id ); function.

    Cheers

    Thread Starter Kim Soler

    (@kimso)

    @caseproof Perfect, thank you.

    Thread Starter Kim Soler

    (@kimso)

    Hi again @caseproof,

    I have found one problem with pagination, it count all post not only the one that current user have permissions to see.

    Thread Starter Kim Soler

    (@kimso)

    Solved,

    I used this function to modify the query with the pre_get_posts hook.

    function custom_get_posts( $query ) {	
    	$user = wp_get_current_user();
    	$user_role = (array) $user->roles;		
    	
    	if( (is_category() || is_archive() || is_search() ) && $query->is_main_query() ) {  
    		$query->set( 'meta_query', array(
    		array(
    		  'key'     => '_members_access_role',
    		  'value'   => $user_role,
    		)
    		) );
    	}
    }
    add_action( 'pre_get_posts', 'custom_get_posts' );

    Just noting here my improved version of the code – the above doesn’t include posts that are totally unrestricted (where the _members_access_role) does not exist.

    add_action( 'pre_get_posts', 'filter_resources_by_user_roles' );
    	function filter_resources_by_user_roles( $query ) {
    		if ( is_admin() || !$query->is_main_query()) {
    		  return;
    		}
    
    		if ( $query->is_tax('resource_type')) {
    		  $query->set('meta_query', array(
    		  	'relation' => 'OR',
    		    array(
    		      'key'     => '_members_access_role',
    		      'value'   => wp_get_current_user()->roles,
    		      'compare' => 'IN',
    		    ),
    		    array(
    		      'key'     => '_members_access_role',
    		      'compare' => 'NOT EXISTS',
    		    )
    		  ));
    		}
    	}
Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Hide Posts from archives pages’ is closed to new replies.