How to create a facet for WP gridbuilder that displays both parent and child custom fields?

12 views Asked by At

Using ACF I created a :

field group: customers repeater field: global_regions repeater sub-field: continents text subfield: continent_name repeater subfield: countries

I have also created posts for this category and populated them with relevant data.

Now I want to create a facet on WPGridBuilder that allows the user to filter the customers either based on continent or country. For example, if they selected North America, then USA and Canada would get selected too but then the user should be able to deselect one if they wanted.

This does not seem to be possible to do within the WPGridBuilder. Could someone please help me with writing a php function for it?

I've tried this code from chagtp and it did not work, the facet it was connected to did not respond to anything in the code.

`add_filter('wp_grid_builder_facet_choices', function ($choices, $facet_id) {
    // Replace 'your_facet_id' with the actual ID of your facet.
    if ('11' == $facet_id) {
        // Adjust 'your_post_type' to match your specific post type.
        $posts = get_posts([
            'post_type' => 'post',
            'numberposts' => -1, // Retrieve all posts
            'fields' => 'ids', // Only get post IDs to improve performance
        ]);

        foreach ($posts as $post_id) {
            // Assuming 'parent_field' is your ACF parent field's key.
            // And 'nested_field' is your repeater or flexible content field.
            // 'sub_field_value' is the sub field within the repeater you want to filter by.
            if (have_rows('group_66019ebed864c', $post_id)) {
                while (have_rows('group_66019ebed864c', $post_id)) {
                    the_row();

                    // Adjust according to your ACF fields' structure
                    if (have_rows('continents')) {
                        while (have_rows('continents')) {
                            the_row();
                            $value = get_sub_field('countries');
                            // Ensure the value does not already exist to avoid duplicates
                            if (!in_array($value, $choices)) {
                                $choices[$value] = $value;
                            }
                        }
                    }
                }
            }
        }
    }
    return $choices;
}, 10, 2);`
0

There are 0 answers