将整个函数复制到要获得平均评分的页面:
<?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;
}
}
?>
关于此函数,我必须提及的几点是:
我不知道the_ratings()
作用此函数应返回一个整数/浮点数,以便代码正常工作。因为我没有插件,所以我无法验证它的输出。如果它不是一个数字,那么您必须将其转换为整数/浮点,或者挖掘插件的代码并找到一个返回数字的函数列表未排序。要对其进行排序,可以使用JavaScript,也可以将输出存储在数组中并使用PHP对其进行排序我在自己的网站上测试了这一点,有超过5000篇帖子分布在500个类别中,代码完成大约需要2秒钟。所以你的情况不会超过一秒钟还有什么事,请告诉我。