WordPress Comment Trashing with Error Handling and Average Rate Calculation
This code snippet is for a WordPress plugin or theme that needs to trash comments and calculate the average rating associated with a product. It uses the get_comment_meta, wp_set_comment_status, and update_post_meta functions to interact with the WordPress database.
The code first retrieves the comment ID from a POST request and then retrieves the associated comment data, including the qq_rate metadata and the post ID. It then fetches all approved comments related to the same product and calculates the average rating from the qq_rate values. Finally, it trashes the original comment using wp_set_comment_status and updates the product's average rating using update_post_meta.
The key improvement in this code is the inclusion of a try-catch block. This ensures that even if there's an error during the process of trashing the comment or updating the product's rating, the code will gracefully handle it. It will log the error message and return a 'ostatus' => 'error' response, helping with debugging and providing users with useful feedback.
Here's a breakdown of the code:
-
Retrieve Comment Data:
$comment_id = $_POST['comment_id'];$qq_rate = get_comment_meta( $comment_id, 'qq_rate', 'true' );$comment_id_data = get_comment( $comment_id );$pid = $comment_id_data->comment_post_ID;
-
Fetch Related Comments:
$args = array('post_type' => 'qqproduct', 'post_id' => $pid, 'status' => 'approve');$comments_query = new WP_Comment_Query;$comments = $comments_query->query( $args );
-
Calculate Average Rating:
$all_rates = array();if ( $comments ) { foreach ( $comments as $comment ) { $comment_idi = $comment->comment_ID; $qq_ratei = get_comment_meta( $comment_idi, 'qq_rate', 'true' ); array_push($all_rates,$qq_ratei); } }$r = array_filter($all_rates);$rate_average = array_sum($r)/count($r);
-
Trash Comment and Update Rating:
- Error Handling:
try { ... } catch (Exception $e) { ... }
wp_set_comment_status( $comment_id, 'trash' );update_post_meta( $pid, 'qq_product_rate', $rate_average);
- Error Handling:
-
Return Response:
$response = array('ostatus' => 'success',);echo json_encode($response);wp_die();
This code provides a robust way to handle comments in a WordPress context, ensuring accurate rating calculations and efficient error handling.
原文地址: https://www.cveoy.top/t/topic/owed 著作权归作者所有。请勿转载和采集!