0

I would like to save some PHP memory when quering category page (like 5000 products at once) with average review rating, so I would like to save average rating of reviews every time I will manually approve new comment.

I would like to accomplish, whenever I click on "APPROVE" button in administration, it will run these php scripts.

function average_rating() {
global $wpdb;

$post_id = get_the_ID();

$ratings = $wpdb->get_results("

    SELECT $wpdb->commentmeta.meta_value

    FROM $wpdb->commentmeta

    INNER JOIN $wpdb->comments on $wpdb->comments.comment_id=$wpdb->commentmeta.comment_id

    WHERE $wpdb->commentmeta.meta_key='rating' 

    AND $wpdb->comments.comment_post_id=$post_id 

    AND $wpdb->comments.comment_approved = 1

    and trim(coalesce($wpdb->commentmeta.meta_value, '')) <>''

    ");

$counter = 0;

$average_rating = 0;    

if ($ratings) {

    foreach ($ratings as $rating) {

        $average_rating = $average_rating + $rating->meta_value;

        $counter++;

    } 

    //round the average to the nearast 1/2 point

    return (round(($average_rating/$counter)*2,0)/2);  

} else {

    //no ratings

    return '0';

}

}

 $ar = average_rating();
 add_post_meta( $post->ID, 'summary', $ar );

1 Answer 1

1

Sadly there are no hooks or filters that you could use in edit-comments.php. You'd have to build your own admin page with a custom button and use wp_set_comment_status( $comment, 'approve' ); to approve comment and do whatever you need to do...

EDIT: I was wrong - there's the wp_set_comment_status action inside wp_set_comment_status function https://wpseek.com/function/wp_set_comment_status/

do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );

So you can just do:

add_action('wp_set_comment_status','average_rating',10,2);

and add to your function

function average_rating($comment_id, $comment_status) {
   if ($comment_status == 'approve') {
      .....rest of your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.