我正在使用此代码查询数组中的所有类别,并对每个类别的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个类别。请你帮我解决一下。
非常感谢。
答案 0 :(得分: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
会显示所有帖子。
答案 1 :(得分: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);
?>
我希望这有助于某人。