Support » Plugin: Members » Globally filter custom post types by current user roles

  • First off, thanks for the excellent plugin.

    Sorry if this question is already addressed somewhere. Searching forums isn’t giving me what I’m after.

    We have a custom post type (CPT) that we’re using and assigning roles to each post using that CPT. Now I’d like to globally filter queries used in various templates to return only posts that the current user should see. In this way, I hope things like pagination and other filters will work as expected. I was just looking at trying posts_where to directly alter the query in my site’s main php, but wonder whether there’s a simpler solution that doesn’t require altering raw SQL.

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • I’m not a seasoned WP dev. Looks like this will work at the template level:

    $user_roles = wp_get_current_user()->roles;

    Then, as part of my posts query (using Timber, in this case)

    'meta_query' => array(
    		array(
    			'key'     => '_members_access_role',
    			'value'   => $user_roles,
    			'compare' => 'IN',
    		),
    	)

    If there is a way to do this at a higher level in my application, or better way, in general, please advise.

    One more way, seems to work:

    add_action( 'pre_get_posts', array( $this, 'filter_posts_by_user_roles' ) );

    
    /**
       * Filter posts by user roles
       * @param {object} $query
       */
      function filter_posts_by_user_roles( $query ) {
        if ( is_admin() ) {
          return;
        }
        if ( $query->is_post_type_archive ) {
          $query->set('meta_query', array(
            array(
              'key'     => '_members_access_role',
              'value'   => wp_get_current_user()->roles,
              'compare' => 'IN',
            ),
          ));
        }
      }
    
    • This reply was modified 2 months, 3 weeks ago by  Josh68.
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.