John Garcia
John Garcia

Reputation: 58

How to filter WP_Query results by the custom field of a related post?

I have two post types:

  1. Venues
  2. Reviews

The Venues Post Type contains the following ACF custom fields:

The Reviews Post Type contains one ACF custom field:

I need to display all Reviews who's Venue is in a specific region and/or Sub Region.

Is this something that can be accomplished using WP_Query? Or do I need to do a fancy database call?

This is what I thought would initially work but it seems that you can not get the custom field of a post object as a meta_query..

$args = array(
  'post_type' => 'review',
  'posts_per_page' => 18,
  'paged' => $paged,
  'meta_key' => 'venue',
  'meta_query' => array(
     array(
       'key' => 'region',
       'value' => 'napa-valley'
     )
   )
);


Upvotes: 3

Views: 5181

Answers (1)

Paul
Paul

Reputation: 1422

I think you need 2 loops here, first loop through the venues using region meta query (you could just use get_posts() or get_pages() instead of WP_Query too) e.g.

'meta_query' => array(
    array(
        'key' => 'region',
        'value' => 'napa-valley'
        )
)

Then you can push the IDs of the venues in specific regions into an array

array_push($venue_ids, $post->ID);

Then you can use the $venue_ids array in your second loop which would loop through the review using a meta query to match the venues from your first loop ids to the post object ids selected in the review page.

'meta_query' => array(
    array(
        'key' => 'venue',
        'value' => $venue_ids
        )
)

Let me know if this is helpful and if you think this will work for you and I can offer further assistance if I haven't explained correctly or you need help.

Upvotes: 7

Related Questions