How to add/update post meta to use in query?
I found a rating system that users can rate the post when commenting. Every thing is good but I want to use the average rating of posts to sort them to users based on average rating (in fact be able to query).
I don't know how I can do that???
The rating_key and rating_value will be saved in wp_commentmeta
table but I want to save the average rating value of every post in wp_postmeta
to be able to query posts based on it.
I can get average rating of every post but I do not how to save and update it in wp_postmeta
as a special key (like avg_post):
?php
$results = $wpdb-get_results("SELECT meta_value FROM wp_commentmeta WHERE meta_key = 'rating' ");
foreach($results as $result){
$rate = $result-meta_value;
$sum +=$rate;
}
$res = $sum/count($results);
$res = number_format((float)$res,1,'.','');
?
.
Update:
I created the new field in my custom comment template so:
add_action('comment_form_logged_in_after','additional_fields');
add_action('comment_form_after_fields','additional_fields');
function additional_fields(){
?
p class="comment-form-rating"
label for="rating"Rating/label
span class="starRting"
?php
for($i=5;$i=1;$i--)
echo 'input id="rating'.$i.'" type="radio" name="rating" value="'.$i.'"label for="rating'.$i.'"/label';
?
/span
/p
Then I saved the rating values in comment_meta
:
function save_comment_meta_phone($comment_id){
if(!empty($_POST['rating']))
$rating = sanitize_text_field($_POST['rating']);
add_comment_meta($comment_id,'rating',$rating);
}
add_action('comment_post','save_comment_meta_phone');
But I need a function to calculate the average rating of every post and save it in post_meta
via a key.
Topic rating comment-meta post-meta Wordpress
Category Web