将查询结果保存到数据库中

时间:2021-03-20 作者:Teymur Abbasov

在多作者网站上,作者发表文章时,可以对自己的文章给予星级评价。我可以使用以下公式显示每个分类术语的平均评级:

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中的平均评级

1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

您可以使用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/

相关推荐

构建具有多个赞的动态WPDB查询

我需要使用多个字符串查询数据库表。只有当;“标签”;列匹配所有字符串。我事先不知道字符串的数量(它是动态的)。我想我很熟悉这段代码,但我没有从数据库中获得任何匹配项: function getMatchingRecipes() { // get the search query: $tags = ($_POST["tagsToSearchWith"]); // clean it up: