1

我正在使用此代码从数组中查询所有类别,并对每个类别的 meta_key 值求和:

<? 
$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);
?>

它工作正常。但我不能只显示 custom_value 总和最多的前 5 个类别。请你帮我解决这个问题。

非常感谢。

4

2 回答 2

1

最后用一点谷歌我明白了:-):

<? $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);         
?>              

我希望这对某人有帮助。

于 2012-07-10T06:44:36.553 回答
1

仅适用于前 5 个帖子

$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将显示所有帖子。

参考。

于 2012-07-10T05:57:20.490 回答