Copy the entire function to the page that you want to have your average ratings:
<?php
// Lets get the id of every existing category
$output_categories = array();
$categories = get_categories($args);
//We loop through every category to calculate the average rating score of it's posts
foreach($categories as $category) {
$post_ids = get_posts(array(
'numberposts' => -1, // get all posts.
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category->cat_ID,
),
),
'fields' => 'ids', // Only get post IDs
));
// Time to calculate the average rating score of each category
if ( $category->count == 0 ){
echo 'Average rating in <a href="'.get_category_link($category->cat_ID).'"> '.$category->cat_name.'</a> is : No rating ';
} else {
$sum = 0;
foreach ($post_ids as $postID) {
$sum += the_ratings($postID);
}
$average_in_cat = (intval($sum / $category->count)*100)/100;
// Alright, we have the average rating score for this category. Let's show it
echo 'Average rating in <a href="'.get_category_link($category->cat_ID).'"> '.$category->cat_name.'</a> is : '.$average_in_cat;
}
}
?>
There are few things that i have to mention about this function, which are:
- I don’t know what is the output of
the_ratings()
function. This function should return an integer / float for the code to work. Since i didn’t have the plugin, i couldn’t verify it’s output. If it’s anything other than a number, then you have to convert it to integer / float, or dig the plugin’s code and find a function that returns a number. - The list is not sorted. To sort it, you can use either JavaScript, or store the output inside an array and use PHP to sort it.
- I tested this on my own website with +5,000 posts distributed over 500 categories, and it took about 2 seconds for the code to finish up. So it won’t take longer than a second in your case.
Anything else, just let me know.