Support

Account

Home Forums ACF PRO Meta_query to check if current user is in relational User field

Solved

Meta_query to check if current user is in relational User field

  • I have a query that checks whether the current user is in the User relational field type. The problem is that the query args return an infinite loop, even though I run if($query->have_posts()).

    Is this the correct way to set up the meta_query? I couldn’t find any documentation on checking the user relational array.

    $query_args = array(
      'numberposts' => -1,
      'post_type' => 'job',
      //Only grab jobs where current user ID is in the team field
      'meta_query' => array(
        'key' => 'team',
        'value' => $current_user->ID,
        'compare' => 'IN',
       )
    );
  • I don’t really see enough here to tell what could be causing an infinite loop. The only error that I see is with the meta_query. If this is a user field then ACF stores a serialized array of user IDs and you need to do something like

    
    $query_args = array(
      'numberposts' => -1,
      'post_type' => 'job',
      //Only grab jobs where current user ID is in the team field
      'meta_query' => array(
        'key' => 'team',
        'value' => '"'.$current_user->ID.'"',
        'compare' => 'LIKE',
       )
    );
    
  • I had initially tried that, but it didn’t work. I discovered that using get_posts() instead of WP_Query() worked, but it required nesting the meta_query inside of a second array.

    Here’s the code that worked for me:

    $job_posts = get_posts(array(
      'post_type' => 'job',
      //Only grab jobs where current user ID is in the team field
      'meta_query' => array(
        array(
          'key' => 'team',
          'value' => '"'.$current_user->ID.'"',
          'compare' => 'LIKE',
        )
       )
    ));
  • Sorry, I completely missed the fact that your meta_query was not formatted correctly in your OP. Yes, meta_query requires a nested array for a value. The same thing you did for get_posts() will work with WP_Query

  • Thanks for that info John. Noted for future loops.

  • Just for record for the future users.

    I tried everything you said before, but I’m allowing multiple values at the relational user field. The only way it works was as I found on this stack: https://wordpress.stackexchange.com/questions/55354/how-can-i-create-a-meta-query-with-an-array-as-meta-field.

    Since the meta_value is a serialized array (on my case), I had to handle it a little differently:

    'meta_query' => array(
        array(
            'key'     => 'my_meta_key',
            'value'   => serialize( strval( get_current_user_id() ) ),
            'compare' => 'LIKE'
        )
    )
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Meta_query to check if current user is in relational User field’ is closed to new replies.