0

I need to get count of different values of meta_key:

Let's say I've got meta_key $class & there's only three different values: 1, 2 & 3.

//My WP_Query 
$ads = new WP_Query(array(
    'post_type' => 'ads', 
    'meta_key' => 'ads_class', 
    'orderby' => 'meta_value_num'
)); 

    if ( $ads->have_posts() ) :

    //Do stuff


//Now I need to know how many have ads_class of "1", "2" and "3" - all as different vars
1
  • You have a loop. Just count as you go. That is a pure PHP problem though and off topic here.
    – s_ha_dum
    Commented Nov 27, 2015 at 1:39

1 Answer 1

0

Just loop over the posts and bump the count based on the value of ads_class:

$ads_1 =
$ads_2 =
$ads_3 = 0;

while ( $ads->have_post() ) {
    $ads->the_post();

    switch ( ( int ) get_post()->ads_class ) {
        case 1 :
            $ads_1++;
            break;
        case 2 :
            $ads_2++;
            break;
        case 3 :
            $ads_3++;
            break;
    }
}

$ads_1; // Number of "1" ads
$ads_2; // Number of "2" ads
$ads_3; // Number of "3" ads

Not the answer you're looking for? Browse other questions tagged or ask your own question.