WordPress Sum meta_values from posts and order them per category

I’m using this code to query all the categories from an array and sum the meta_key values per category:

<? 
$arr_cat = array(1,34,64,32);
foreach ($arr_cat as $cat) {
  $MySum = 0;
  $args = array(
    'cat' => $cat,
    'meta_key' => 'proyecto_votos',
    'post_type' => 'proyecto',
    'posts_per_page' => '-1');
    $the_query = new WP_Query( $args);
    while ( $the_query->have_posts() ) : $the_query->the_post();
      $MySum += get_post_meta($post->ID, 'proyecto_votos', true);
    endwhile;
    wp_reset_postdata();
  }
  //var_dump($arr_cat);
?>

And it works ok. But I can’t show only the top 5 categories with most sum of custom_value. Please can you help me out on this.

Read More

Thanks so much.

Related posts

Leave a Reply

2 comments

  1. Only for top 5 posts

    $args = array(
        'cat' => $cat,
        'post_type' => 'proyecto',
        'meta_key' => 'proyecto_votos',
        'orderby'='meta_value_num',
        'posts_per_page' => '5'  // top 5 posts using ASC order by default
    );
    

    posts_per_page => -1 will show all posts.

    Reference.

  2. Finally with a little bit of google i got it :-):

    <? $totalvotes = get_meta_values( 'proyecto_votos', 'proyecto' ); ?>    
    <? 
    foreach ($arr_cat_reg as $cat) {
        $MySum = 0;
        $args = array(
        'cat' => $cat,
        'meta_key' => 'proyecto_votos',
        'post_type' => 'proyecto',
        'posts_per_page' => '-1' );        
        $the_query = new WP_Query( $args);
        while ( $the_query->have_posts() ) : $the_query->the_post();
            $MySum += get_post_meta($post->ID, 'proyecto_votos', true);
        endwhile;       
        //echo $MySum.'<br/>';              
        $percent = $MySum * 100;
        $percent = $percent / $totalvotes;              
        //echo $percent;                
        wp_reset_postdata();
        $catslug = get_cat_slug($cat);
        $most_voted[] = array('region' => $catslug, 'votos' => $MySum); 
    }               
    $sortArray = array();
    
    foreach($most_voted as $region){
        foreach($region as $key=>$value){
            if(!isset($sortArray[$key])){
                $sortArray[$key] = array();
            }
            $sortArray[$key][] = $value;
        }
    } 
    $orderby = "votos";
    array_multisort($sortArray[$orderby],SORT_DESC,$most_voted); 
    $top5 = array_slice($most_voted, 0, 5);         
    ?>              
    

    I Hope this helps somebody.