Question

in multi author website when author publish post , he/her can give star rating to his/her own post. and I can display average rating for every taxonomy term using this formula:

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>

But I also need to save average rating result into db for current taxonomy term. thatswhy i created custom meta field for taxonomy terms ( Example: avareage_star_rating) . But how can I save average rating in db automaticly

Was it helpful?

Solution

You can save term meta using update_term_meta:

update_term_meta( int $term_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )

https://developer.wordpress.org/reference/functions/update_term_meta/

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top