Support

Account

Home Forums General Issues get_users with array value for meta_query value in

Helping

get_users with array value for meta_query value in

  • Hi. I have a scenario where I need to see if the value(s) for a Post Object field in a user’s profile has any matches in an array of possible values. Confusing I know…

    So users might be associated with multiple “Companies” (acf key “company”) which is a Post Object field. A user could have multiple Companies so it ends up being an array. I want to return all users who have at least one match to the current user’s companies

    $args = array(
    ‘meta_query’ => array(
    array(
    ‘key’ => ‘company’,
    ‘value’ => $company_names, // arrary of current user’s company IDs
    ‘compare’ => ‘IN’ // If I use “LIKE” it returns ALL users. “IN” returns none
    )
    )
    );

    $member_arr = get_users($args); // I expect this to return user’s who have at least one company that matches the current user’s list of companies.

    It’s like I need array_intersect as a Compare option and “IN” apparently doesn’t work like that. I suppose I could to a foreach with a get_users for each of the company IDs but that seems awfully inefficient. There’s probably also a slick way to do this via an sql query but i’m not quite savvy enough yet with those to piece one together.

    Any thoughts?

  • First thing is that an ACF post object field does not store the name of the related post. It stores the post ID of that post. So if you are searching the post object field you need to use post IDs and not names.

    Second, because you have the post object field set to allow multiple selections ACF stores those selections as a serialized array in a single row of the database. This array cannot be search the same way as a standard WP custom field.

    https://www.advancedcustomfields.com/resources/querying-relationship-fields/

    
    $meta_query = array('relation' => 'OR');
    foreach ($companies as $post_id) {
      $meta_query(
        'key' => 'company',
        'value' => '"'.$post_id.'"'.
        'compare' => 'LIKE'
      }
    }
    $args['meta_query'] = $meta_query;
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.