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
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' ) )
The topic ‘Meta_query to check if current user is in relational User field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.