今天写一个功能的时候需要考虑到评论的状态变化,比如提交评论、删除评论、评论通过等等关于评论相关的状态变化,但是我没有找到一个有效的函数或者相关内容来整体管理,于是乎只能求助谷歌了,搜索一番之后,了解到看来不是我一个人的问题。
图片所示,是九年前的内容,但是很幸运的就只作者在2020年6月的时候更新了一次,结果如下:
所以说国外的WordPress的开发者是真的比较敬业了,他完全没有理由也没有衣服去更新,希望国内的开发者们也能像国外一样吧。
add_action('edit_comment', 'update_business_rating_avg'); add_action('comment_post', 'update_business_rating_avg'); add_action('comment_unapproved_to_approved', 'update_business_rating_avg'); add_action('comment_approved_to_unapproved', 'update_business_rating_avg'); add_action('comment_spam_to_approved', 'update_business_rating_avg'); add_action('comment_approved_to_spam', 'update_business_rating_avg'); add_action('comment_approved_to_trash', 'update_business_rating_avg'); add_action('comment_trash_to_approved', 'update_business_rating_avg'); function update_business_rating_avg($comment){ if ( !is_object( $comment ) ){ $comment = get_comment( $comment ); } $post_id = $comment->comment_post_ID; $post_type = get_post_type($post_id); if('business' == $post_type){ $avg = 0; global $wpdb; $query = "SELECT AVG(meta_value) FROM $wpdb->commentmeta "; $query .= "INNER JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID " ; $query .= "WHERE $wpdb->commentmeta.meta_key = 'rating' "; $query .= "AND $wpdb->comments.comment_approved = 1 "; $query .= "AND $wpdb->comments.comment_post_ID = '$post_id'"; if( $result = $wpdb->get_var($wpdb->prepare($query)) ){ $avg = roundToNearestFraction($result, 0.5); update_post_meta($post_id, 'avg_rating', $avg); }else{ // report error //$wpdb->print_error(); } } }
这里我们不用在于功能函数是什么内容,我主要是想告诉大家关于WordPress中评论相关的钩子有哪些,希望大家能用到。