WordPress meta_query with ACF relationship field

I have a WP custom post type that contains Employee Bio information. Because we don't want to create accounts in wp_users for everyone, this data is implemented as a "regular" CPT living in wp_posts. Let's say I have a row with ID 250 for employee Scott. We also have normal blog posts. Since we're not using regular WP users, we can't take advantage of the usual metadata and relationships to associate authors with posts. So instead, we have a custom field, "af_author", created with an ACF Relationship field type. When we create a post, we choose an author from the list of Employee Bio objects. On the page that displays the bio information for an employee, we want to include a list of posts that the employee has authored. So when I'm looking at the Employee Bio page for Scott (ID = 250), I want to do a query loop to retrieve all Posts that have been written by ID = 250. Who the post is written by is stored in the related custom field "af_author" for each post. The field itself is an array of IDs; ID 250 would need to be "IN" the array. I'm having trouble figuring out how to code the meta query for this. The code below is executed while creating the Employee Bio page, so if employee Scott is being displayed, get_the_ID() would return 250. I have tried the following code with no success: $new_query_args = [ 'meta_query' => [ [ 'key' => 'af_author', 'value' => get_the_ID(), 'compare' => 'IN', ] ] ]; $query_args = array_merge( $query_args, $new_query_args ); How do I make this work?

Comment (1)

Jese Leos

August 10, 2024

Verified user

Based on WordPress query by ACF relationship field, I was able to fix this by changing the 'compare' => 'IN' to 'compare' => 'LIKE'. So the resultant code looks like this: $new_query_args = [ 'meta_query' => [ [ 'key' => 'af_author', 'value' => get_the_ID(), 'compare' => 'LIKE', ] ] ]; $query_args = array_merge( $query_args, $new_query_args ); I'm not exactly sure why this works, but it fixed the problem.

You’ll be in good company