在多作者网站上,作者发表文章时,可以对自己的文章给予星级评价。我可以使用以下公式显示每个分类术语的平均评级:
AVERAGE RATING=TOTAL STAR RATING SUM / TOTAL POST COUNT IN CURRENT TAXONOMY TERM ARCHIVE.
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<span id=stars></span>
<?php
$term_slug = get_queried_object()->slug;
$args = array(
\'posts_per_page\' => -1, // Number of posts per page
\'post_type\' => array(\'A-CPT\',\'B-CPT\'), // Custom Post Types
\'tax_query\' => array(
array(
\'taxonomy\' => \'MY-TAXONOMY-SLUG-NAME\', //Custom Taxonomy Name
\'field\' => \'slug\',
\'terms\' => array(
$term_slug
)
)
)
);
$new = new WP_Query( $args );
$count = $new->post_count; // Total post count
if ( have_posts() ) while ($new->have_posts()) : $new->the_post(); ?>
<?php
$post_id = get_the_ID();
$post_rating = get_post_meta( $post_id, \'ratings_3421372395\', true ); // getting rating metavalues from posts
?>
<?php
if (!empty($post_rating)){
$reviewsNum += $post_rating;
}
?>
<?php endwhile; // end of the loop. ?>
<?php
$averagerating = $reviewsNum / $count; ?>
<?php //echo $count; ?>
<?php // echo $reviewsNum; ?>
<script>
document.getElementById("stars").innerHTML = getStars(<?php echo $averagerating;
?>);
function getStars(rating) {
// Round to nearest half
rating = Math.round(rating * 2) / 2;
let output = [];
// Append all the filled whole stars
for (var i = rating; i >= 1; i--)
output.push(\'<i class="fa fa-star" aria-hidden="true" style="font-size: 20px; color: green;"></i> \');
// If there is a half a star, append it
if (i == .5) output.push(\'<i class="fa fa-star-half-o" aria-hidden="true" style="font-size: 20px; color: green;"></i> \');
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--)
output.push(\'<i class="fa fa-star-o" aria-hidden="true" style="font-size: 20px; color: green;"></i> \');
return output.join(\'\');
}
</script>
但我还需要将当前分类术语的平均评级结果保存到db中。这就是为什么我为分类术语创建了自定义元字段(例如:avareage\\u star\\u rating)。但是我如何自动保存db中的平均评级