$terms = get_terms( array(
'taxonomy' => 'category',
'hide_empty' => false,
) );
$sort = array();
//loop to list through all category
foreach ( $terms as $term ) {
$id = $term->ID;
$name = $term->name;
$args = array(
'post_type' => 'post',
'category' => $name,
);
$query = new WP_Query( $args );
$sum = 0;
if ($query->have_posts() ):while ($query->have_posts() ):$query->the_post();
// to add all the values of the custom field
$sum += get_post_meta( get_the_ID(), '_postviews ', true );
endwhile;
//adds term name and the total sum of all _postviews meta in array the term name as key abnd the sum as its value
$sort[ $name ] = $sum;
endif;
//sort keys based on values HIGH TO LOW
}
arsort( $sort );
print_r( $sort );
Theoretically the above code should work as
- It loops through your category
- Gets post based on your category
- Get post most meta and store add them in the variable sum
- Once all the post have been checked and stored in a variable sum, they are now stored as array in the variable $sort
Could you please let me know if this code worked for you or not