0

I have a custom post type called Projects that includes an ACF field named team_members which uses User as a field type and returns a User Array. I want to filter the post type listing so that the current logged-in user sees only records that contain their data in the team_members field.

I am trying to use this query, but it returns all the records:

add_action('pre_get_posts', 'filter_posts_list');
function filter_posts_list($query)
{
    //$pagenow holds the name of the current page being viewed
    global $pagenow, $typenow;  

    //$current_user uses the global
    global $current_user;

    //Shouldn't happen for the admin, but for any role with the edit_posts capability and only on the posts list page, that is edit.php
    if(!current_user_can('administrator') && current_user_can('edit_posts') && ('edit.php' == $pagenow) &&  $typenow == 'projects') { 

        $current_user_id = $current_user->ID;
        
        $query->set( 'meta_query', array(
            array(
                'key'     => 'team_members',
                'value'   => $current_user_id,
                'compare' => "LIKE"
            ),
        ));
    
    }
}

Here is my custom field team_members:

custom field

And here is the example of a post from custom post type Projects:

enter image description here

How can I query only by the ACF field team_members that has the exact user ID as the current user in the post?

2
  • note that if this is a single post meta value that stores all the values then that will mean significant scope for false positives, e.g. searching for a user with 10 will also find users with 110 2100 and 103. This becomes trivial if they're stored as separate post meta with the same key though. Fundamentally using an ACF field to filter/search like this is going to be very bad for performance, this kind of filtering is what custom taxonomies are meant to be used for, not post meta
    – Tom J Nowell
    Commented Dec 7, 2023 at 15:46
  • Hey, thanks for the heads-up on the potential issues with using ACF fields for filtering. I get that it might lead to some false positives, and I'm all ears for better solutions. You mentioned custom taxonomies – sounds interesting! Any tips or resources on how to set those up for my situation? I'm a bit new to this, so any help is much appreciated! Commented Dec 8, 2023 at 5:33

0

Your Answer

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