Only show first post to match certain criteria within WP_Query

Based on the comments I think I’d implement this outside of the query itself, and use PHP to filter the results. I’ll give you a second solution as well, but I think this first one is easier to understand (when you come back to it later on).

Since I don’t know the specifics of your code, here’s a pseudocode approach.

$unique_fields_array = array();

// you loop will contain all custom post types regardless of custom field values
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();

        // get the custom field for this specific post
        $meta_value = get_post_meta( $the_query->post->ID, 'size', true );

        // if we've never output a post with this custom field value yet, do it now, and then add it to the unique_fields_array
        if ( !in_array($meta_value, $unique_fields_array) ) {

            // OUTPUT YOUR POST CONTENT HERE

            $unique_fields_array[] = $meta_value;
        }
    }
}

// restore original postdata
wp_reset_postdata();

A second solution would be to bypass WP_Query all together (and I would not recommend it, but here it is anyway).

global $wpdb;
$values = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta pm, $wpdb->post p WHERE meta_key  = 'size' and pm.post_id=p.ID and p.post_type="my_custom_postype" ", ARRAY_A);

You can then loop your $values in PHP and they’ll only contain records where the size was unique. Of course, you can customize this SQL with a sort, additional filters, etc.

Leave a Comment