Search code examples
wordpressadvanced-custom-fieldsacfpro

ACF query for custom field in relation


There's a custom post type called "events" and another post type called "venues". The post type "events" has a relation field for "venues" so that the user can select the venue when setting up an event.

"venue" has a custom text field "city".

I need now to search for all events that are in a specific city. With meta_query it doesn't work, the results are always empty:

$query->set('meta_query', array(
    array(
        'key'       => 'city',
        'value'     => 'New York',
        'compare'   => 'LIKE', 
    ),
));

How can I find all events where the city of the connected venue is equal to "New York"? Thanks a lot!


Solution

  • Get your venues from the desired city first...

    $args = array(
        'posts_per_page'    => -1,
        'fields' => 'ids',
        'post_type'        => 'venues',
        'meta_query'    => array(
           array(
            'key'       => 'city',
            'value'     => '"New York"',
            'compare'   => 'LIKE', 
           )
        ),
    );
    $venues_ids = get_posts($args);
    

    Then query your events from the matched venues

        $args = array(
            'posts_per_page'    => -1,
            'post_type'        => 'events',
            'meta_query'    => array(
               array(
                'key'       => 'venues',
                'value'     => $venues_ids,
                'compare'   => 'IN', 
               )
            ),
        );
        $events = get_posts($args);