phpwordpressfilteradvanced-custom-fieldsmeta-query

Query get_posts array must contain at least 3 posts that have specific ACF meta value


I am trying to extract posts that contain no less than 3 records that contain a certain value in an ACF meta key.

I have a list of employees that we are displaying on the site using:

$posts = get_posts(array(
    'post_type' => 'team_member',
    'post_status' => 'publish',
    'orderby'   => 'rand',
    'posts_per_page' => 20, 
));

However I now need to introduce a query that ensures that at least 3 ladies are displayed within this list at any given time. I have setup an acf field gender with values male and female to capture this, but am unable to get the correct meta value query structure in place.

$posts = get_posts(array(
    'post_type' => 'team_member',
    'post_status' => 'publish',
    'orderby'   => 'rand',
    'posts_per_page' => 20, 
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'gender',
            'value'     => 'female',
            'compare'   => '>'
        )
    )
));

Solution

  • I took a different direction and created to seperate queries that I combined, this seemed to work fine.

    $male_posts = get_posts(array(
        'post_type' => 'team_member',
        'meta_key'=> 'gender',
        'meta_value'=> 'male',
        'post_status' => 'publish',
        'orderby'  => 'rand',
        'posts_per_page' => 15, 
    ));
    $female_posts = get_posts(array(
        'post_type' => 'team_member',
        'meta_key'=> 'gender',
        'meta_value'=> 'female',
        'post_status' => 'publish',
        'orderby'  => 'rand',
        'posts_per_page' => 3, 
    ));
    $all_posts = array_merge( $male_posts, $female_posts );
    $all_posts_ids = wp_list_pluck( $all_posts, 'ID' );
    $posts = get_posts( array(
        'post__in'  => $all_posts_ids,
        'post_type'  => 'team_member',
        'post_status' => 'publish',
        'orderby'  => 'rand',
        'posts_per_page' => -1
    ));