add_action('wp_ajax_submit_book_rating', 'submit_book_rating'); add_action('wp_ajax_nopriv_submit_book_rating', 'submit_book_rating'); function submit_book_rating() { if ( ! isset($_POST['product_id'], $_POST['rating']) ) { wp_send_json_error(); } $product_id = intval($_POST['product_id']); $rating = intval($_POST['rating']); if ( $rating < 1 || $rating > 5 ) { wp_send_json_error(); } // جلوگیری از رأی تکراری (IP + Cookie) $ip = $_SERVER['REMOTE_ADDR']; $cookie_key = 'book_rated_' . $product_id; if ( isset($_COOKIE[$cookie_key]) ) { wp_send_json_error(['message' => 'already_rated']); } // ساخت review واقعی ووکامرس $commentdata = array( 'comment_post_ID' => $product_id, 'comment_author' => 'Guest', 'comment_content' => '', 'comment_type' => 'review', 'comment_approved'=> 1, 'comment_author_IP' => $ip, ); $existing = get_comments([ 'post_id' => $product_id, 'author_ip' => $ip, 'type' => 'review', 'count' => true ]); if ($existing > 0) { wp_send_json_error(['message' => 'already_rated']); } $comment_id = wp_insert_comment($commentdata); if ( ! $comment_id ) { wp_send_json_error(); } // ذخیره امتیاز add_comment_meta($comment_id, 'rating', $rating, true); // آپدیت متای ووکامرس wc_update_product_rating($product_id); // کوکی (۳۰ روز) setcookie($cookie_key, $rating, time() + MONTH_IN_SECONDS, '/'); wp_send_json_success([ 'rating' => $rating, 'average' => wc_get_rating_html( wc_get_product($product_id)->get_average_rating() ) ]); }