Display several random posts, but make sure a condition is met

I think the best way here would be to run three separate loops here (you can also do two loops, but then you need to get full posts in the men and women queries, combine them and shuffle them), the first two will be used to get 5 men and the second loop will get 2 women. You can adjust this as necessary. The third loop will use the info from the first two loops to get the full posts.

Here I accept that you are using a custom field which has two separate values, one for men and one for women. Also, I accept that you don’t need to paginate this query.

You can try something like this

/*
 * First query to get 5 men. Only get post ID's to increase performance
 */
$args1 = array(
    'posts_per_page'   => 5,
    'orderby'          => 'rand',
    'suppress_filters' => true,
    'no_found_rows'    => true,
    'fields'           => 'ids',
    'meta_query'       => array(
        array(
            'key'   => 'custom-field-name',
            'value' => 'value-for-men',
        )
    )
);
$men = new WP_Query( $args1 );

/*
 * Second query to get 2 women. Only get post ID's to increase performance
 */
$args2 = array(
    'posts_per_page'   => 2,
    'orderby'          => 'rand',
    'suppress_filters' => true,
    'no_found_rows'    => true,
    'fields'           => 'ids',
    'meta_query'       => array(
        array(
            'key'   => 'custom-field-name',
            'value' => 'value-for-women',
        )
    )
);
$women = new WP_Query( $args2 );

/*
 * Merge the post id's from the two queries
 */
$merged_ids = array_merge( $women->posts, $men->posts );

/*
 * Use the merged array of post id's to get the complete posts. Use 'orderby' => 'post__in'
 * to keep shuffled order of the posts that will be returned
 */ 
$args3 = array( 
    'post__in' => shuffle( $merged_ids ),
    'orderby' => 'post__in'
);
$merged_queries = new WP_Query( $args3 ); 

?><pre><?php var_dump($merged_queries->posts); ?></pre><?php    

Leave a Comment