Query Posts by Meta Value array count from Relationship field (ACF) on WordPress

390 views Asked by At

I have a relationship field "assigned_brands" on Stylist Post type that returns an array of the associated Brands post type. I want to query based on the count of assigned_brands . For example I want to get only the the Stylists that have between 1-3 assigned brands or get the stylists that have 10 or more brands assigned

Do you have any idea what filter I must use to be able to use a meta query ?

Thank you all in advance Kind regards John

1

There are 1 answers

0
Dimitrios Pantazis On

You cant achieve what you would like without one more custom field. Use a function like the one below to store to a different field the count() of your relationship field.

add_action( 'acf/save_post', 'count_fields_values_after_save', 20 );
function count_fields_values_after_save( $post_id ) {
    if ( 'stylist' === get_post_type( $post_id ) ) {
        $num = 0;
        $brands = get_field( 'assigned_brands', $post_id );
        if ( ! empty( $brand ) && is_array( $brands ) ) {
            $num = count( $brands );
        }
        update_post_meta( $post_id, '_count_assigned_brands', $num );
    }
}

Then you can use the WP_Query class to query this extra custom field.

'meta_query' => [
    [
         'key' => '_count_assigned_brands',
         'value' => 3,
    ],
],

Everything above is not tested, but they seem ok to me and it should work!