Group posts that matches a term in a loop

This is my best approach: Store the values in an array during the while loop, and then using array_count_values php function, you obtain the desired output.

It is untested, but I think it should work:

if ( $query->have_posts() ) {

    //in this variable, declared as an array, we will store the values
    $products_array = array();

    while ( $query->have_posts() ) : $query->the_post();

        $terms = get_the_terms( $post->ID , 'brand' );
        if ( $terms && ! is_wp_error( $terms ) ) {
            $brand_name = $terms[0]->name;
        }
        $products_array[] = $brand_name;

    endwhile;

    wp_reset_query();

}

//At this point, the $products_array, should be more or less:
//array(brandA, brandB, brandC, brandB, brandB, brandB, brandA);

//array_count_values does the magic
$result = array_count_values($products_array);

foreach ($result as $key => $value) {

    echo $key . ' has ' . $value . ' products.<br/>';

}

Hope it helps!

Leave a Comment