Home Forums General Issues Query fields from posts related to relation?


Query fields from posts related to relation?

  • Hi, how do I query Fields from CPT that is in relationship to a relationship?

    here’s the scenario:

    I have 3 CPT – Vacations, Cities, Activities.

    Each vacation has cities attached via relationship, and each city has Activities attached also via relationship.

    Inside each vacation tmeplate I need to query its city (works) and its activities (not working). The obvious solution people suggest is creating a relationship from Vacations to activities, but that is not an option since there are MANY activities and vacations, and that would mean lots of duplication, and potentially lots of errors.

    So how can i, inside vacation template, query activities via relationship with Cities? This is how I adapted the code from ACF website, but it’s not working, and field keys are correct.

    I am working inside Bricks builder and ACF, nothing else.

    add_filter('bricks/posts/query_vars', function($query_vars, $settings, $element_id) {
        if ($element_id == 'vtwrnt' && function_exists('get_field')) {
            // Get related Cities to the current Vacation
            $related_cities = get_field('field_64948f50129ec'); // Replace 'related_cities_field' with your Cities field key
            $related_activities = array();
            foreach ($related_cities as $city_id) {
                // Get related Activities to the current City
                $city_activities = get_field('field_64ab8ce141d45', $city_id); // Replace 'related_activities_field' with your Activities field key
                // Merge the activities arrays
                $related_activities = array_merge($related_activities, $city_activities);
            $query_vars['post__in'] = $related_activities;
    		 $query_vars['post_type'] = 'activity';
        return $query_vars;
    }, 10, 3);
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.