文章目录[隐藏]
实操指南:构建商品评论与问答接口的3个互动策略
引言:为什么商品评论与问答如此重要?
在当今电商环境中,商品评论和用户问答已成为影响购买决策的关键因素。研究表明,超过90%的消费者在购买前会查看商品评价,而带有用户问答的商品页面转化率平均高出15%。对于WordPress电商网站来说,一个设计良好的评论与问答系统不仅能提升用户体验,还能显著增加用户参与度和转化率。
本文将基于WordPress开源系统,通过三个核心互动策略,详细讲解如何构建功能丰富、用户友好的商品评论与问答接口。无论您是刚入行的开发者还是有一定经验的程序员,都能从本文中找到实用的代码实现方案。
策略一:分层结构化评论系统
1.1 传统评论系统的局限性
WordPress自带的评论系统虽然简单易用,但在电商场景中存在明显不足:
- 缺乏评分功能
- 无法上传图片/视频
- 没有评论有用性投票
- 缺少商家回复功能
1.2 扩展WordPress评论数据表
首先,我们需要扩展默认的评论表结构,添加电商所需的字段:
// 在主题的functions.php或自定义插件中添加
function add_product_comment_meta_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'product_comment_meta';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
meta_id bigint(20) NOT NULL AUTO_INCREMENT,
comment_id bigint(20) NOT NULL,
rating tinyint(1) DEFAULT 0,
helpful_count int(11) DEFAULT 0,
unhelpful_count int(11) DEFAULT 0,
image_urls text,
is_verified_purchase tinyint(1) DEFAULT 0,
PRIMARY KEY (meta_id),
KEY comment_id (comment_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'add_product_comment_meta_table');
1.3 实现星级评分系统
// 在评论表单中添加评分字段
function add_rating_field_to_comment_form() {
if (is_singular('product')) {
echo '<div class="comment-form-rating">
<label for="rating">评分 <span class="required">*</span></label>
<div class="rating-stars">
<input type="radio" id="star5" name="rating" value="5" />
<label for="star5" title="5星"></label>
<input type="radio" id="star4" name="rating" value="4" />
<label for="star4" title="4星"></label>
<input type="radio" id="star3" name="rating" value="3" />
<label for="star3" title="3星"></label>
<input type="radio" id="star2" name="rating" value="2" />
<label for="star2" title="2星"></label>
<input type="radio" id="star1" name="rating" value="1" />
<label for="star1" title="1星"></label>
</div>
</div>';
}
}
add_action('comment_form_top', 'add_rating_field_to_comment_form');
// 保存评分数据
function save_comment_rating($comment_id) {
if (isset($_POST['rating']) && $_POST['rating']) {
$rating = intval($_POST['rating']);
add_comment_meta($comment_id, 'rating', $rating);
// 更新商品平均评分
$post_id = get_comment($comment_id)->comment_post_ID;
update_product_average_rating($post_id);
}
}
add_action('comment_post', 'save_comment_rating');
// 计算商品平均评分
function update_product_average_rating($post_id) {
$comments = get_comments(array('post_id' => $post_id));
$total_rating = 0;
$rating_count = 0;
foreach ($comments as $comment) {
$rating = get_comment_meta($comment->comment_ID, 'rating', true);
if ($rating) {
$total_rating += intval($rating);
$rating_count++;
}
}
if ($rating_count > 0) {
$average_rating = round($total_rating / $rating_count, 1);
update_post_meta($post_id, '_average_rating', $average_rating);
update_post_meta($post_id, '_rating_count', $rating_count);
}
}
1.4 实现评论图片上传功能
// 添加上传图片字段
function add_image_upload_to_comment_form() {
if (is_singular('product')) {
wp_enqueue_script('comment-image-upload', get_template_directory_uri() . '/js/comment-upload.js', array('jquery'), '1.0', true);
echo '<div class="comment-form-images">
<label for="comment_images">上传图片 (最多3张)</label>
<input type="file" name="comment_images[]" id="comment_images" multiple accept="image/*" />
<div id="image-preview"></div>
</div>';
}
}
add_action('comment_form_after_fields', 'add_image_upload_to_comment_form');
// 处理图片上传
function handle_comment_image_upload($comment_id) {
if (!empty($_FILES['comment_images'])) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$image_urls = array();
$files = $_FILES['comment_images'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$upload_overrides = array('test_form' => false);
$uploaded_file = wp_handle_upload($file, $upload_overrides);
if (!isset($uploaded_file['error'])) {
$image_urls[] = $uploaded_file['url'];
}
}
}
if (!empty($image_urls)) {
add_comment_meta($comment_id, 'comment_images', $image_urls);
}
}
}
add_action('comment_post', 'handle_comment_image_upload');
策略二:智能问答与互动机制
2.1 创建独立的问答系统
与评论系统不同,问答系统需要更结构化的数据组织:
// 创建问答自定义表
function create_product_qa_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'product_qa';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
qa_id bigint(20) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
question text NOT NULL,
answer text,
asked_by bigint(20),
answered_by bigint(20),
asked_date datetime DEFAULT CURRENT_TIMESTAMP,
answered_date datetime,
helpful_count int(11) DEFAULT 0,
is_anonymous tinyint(1) DEFAULT 0,
status enum('pending','answered','hidden') DEFAULT 'pending',
PRIMARY KEY (qa_id),
KEY product_id (product_id),
KEY status (status)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'create_product_qa_table');
2.2 实现问答提交与显示功能
// 问答提交表单
function display_product_qa_form() {
if (is_singular('product')) {
global $post;
echo '<div class="product-qa-form">
<h3>有问题?问问其他买家</h3>
<form id="qa-form" method="post">
<input type="hidden" name="product_id" value="' . $post->ID . '">
<div class="form-group">
<textarea name="question" placeholder="输入您的问题..." rows="3" required></textarea>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_anonymous" value="1">
匿名提问
</label>
</div>
<div class="form-group">
<button type="submit" name="submit_question">提交问题</button>
</div>
</form>
</div>';
// 显示已有问答
display_product_qa_list($post->ID);
}
}
add_action('woocommerce_after_single_product_summary', 'display_product_qa_form', 15);
// 处理问答提交
function handle_question_submission() {
if (isset($_POST['submit_question']) && !empty($_POST['question'])) {
global $wpdb, $current_user;
$table_name = $wpdb->prefix . 'product_qa';
$product_id = intval($_POST['product_id']);
$question = sanitize_textarea_field($_POST['question']);
$is_anonymous = isset($_POST['is_anonymous']) ? 1 : 0;
$user_id = $is_anonymous ? 0 : $current_user->ID;
$wpdb->insert(
$table_name,
array(
'product_id' => $product_id,
'question' => $question,
'asked_by' => $user_id,
'is_anonymous' => $is_anonymous,
'status' => 'pending'
),
array('%d', '%s', '%d', '%d', '%s')
);
// 发送通知给管理员
send_qa_notification_email($product_id, $question);
echo '<div class="notice success">问题已提交,我们会尽快回复!</div>';
}
}
add_action('init', 'handle_question_submission');
// 显示问答列表
function display_product_qa_list($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'product_qa';
$qa_items = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $table_name WHERE product_id = %d AND status != 'hidden' ORDER BY answered_date DESC, asked_date DESC",
$product_id
));
if ($qa_items) {
echo '<div class="product-qa-list">';
echo '<h3>买家问答 (' . count($qa_items) . ')</h3>';
foreach ($qa_items as $qa) {
echo '<div class="qa-item">';
echo '<div class="question">';
echo '<strong>问:</strong>' . esc_html($qa->question);
echo '<span class="qa-meta">' . get_qa_meta_display($qa) . '</span>';
echo '</div>';
if ($qa->answer) {
echo '<div class="answer">';
echo '<strong>答:</strong>' . esc_html($qa->answer);
echo '<span class="qa-meta">' . date('Y-m-d', strtotime($qa->answered_date)) . '</span>';
echo '</div>';
}
echo '<div class="qa-actions">';
echo '<button class="helpful-btn" data-qa-id="' . $qa->qa_id . '">有帮助 (' . $qa->helpful_count . ')</button>';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
}
2.3 实现问答智能推荐
// 基于相似问题的智能推荐
function get_similar_questions($product_id, $current_question, $limit = 3) {
global $wpdb;
$table_name = $wpdb->prefix . 'product_qa';
// 简单的关键词匹配(实际项目中可以使用更复杂的算法)
$keywords = explode(' ', preg_replace('/[^w]/', ' ', $current_question));
$keywords = array_filter($keywords, function($word) {
return strlen($word) > 2;
});
if (empty($keywords)) {
return array();
}
$like_conditions = array();
foreach ($keywords as $keyword) {
$like_conditions[] = $wpdb->prepare("question LIKE %s", '%' . $wpdb->esc_like($keyword) . '%');
}
$like_query = implode(' OR ', $like_conditions);
$similar_questions = $wpdb->get_results($wpdb->prepare(
"SELECT question, answer, helpful_count
FROM $table_name
WHERE product_id = %d
AND status = 'answered'
AND ($like_query)
ORDER BY helpful_count DESC
LIMIT %d",
$product_id, $limit
));
return $similar_questions;
}
// 在问答表单前显示相似问题
function display_similar_questions_before_form() {
if (is_singular('product') && isset($_GET['show_qa_form'])) {
global $post;
$current_question = isset($_POST['question']) ? $_POST['question'] : '';
if ($current_question) {
$similar_questions = get_similar_questions($post->ID, $current_question);
if ($similar_questions) {
echo '<div class="similar-questions">';
echo '<h4>以下问题可能对您有帮助:</h4>';
echo '<ul>';
foreach ($similar_questions as $sq) {
echo '<li>';
echo '<div class="similar-question">' . esc_html($sq->question) . '</div>';
if ($sq->answer) {
echo '<div class="similar-answer">' . wp_trim_words($sq->answer, 20) . '</div>';
}
echo '</li>';
}
echo '</ul>';
echo '</div>';
}
}
}
}
add_action('woocommerce_before_single_product', 'display_similar_questions_before_form');
策略三:用户激励与社区互动
3.1 建立评论有用性投票系统
// 记录用户投票行为
function track_helpful_votes() {
global $wpdb;
$table_name = $wpdb->prefix . 'comment_votes';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
vote_id bigint(20) NOT NULL AUTO_INCREMENT,
comment_id bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
vote_type enum('helpful','unhelpful') NOT NULL,
vote_date datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (vote_id),
UNIQUE KEY user_comment_vote (user_id, comment_id),
KEY comment_id (comment_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'track_helpful_votes');
// AJAX处理投票
function handle_helpful_vote_ajax() {
check_ajax_referer('vote_nonce', 'security');
$comment_id = intval($_POST['comment_id']);
$vote_type = sanitize_text_field($_POST['vote_type']);
$user_id = get_current_user_id();
if (!$user_id) {
wp_die('请登录后投票');
}
global $wpdb;
$votes_table = $wpdb->prefix . 'comment_votes';
// 检查是否已投票
$existing_vote = $wpdb->get_var($wpdb->prepare(
"SELECT vote_type FROM $votes_table WHERE comment_id = %d AND user_id = %d",
$comment_id, $user_id
));
if ($existing_vote) {
if ($existing_vote == $vote_type) {
// 取消投票
$wpdb->delete($votes_table,
array('comment_id' => $comment_id, 'user_id' => $user_id),
array('%d', '%d')
);
$change = -1;
} else {
// 更改投票
$wpdb->update($votes_table,
array('vote_type' => $vote_type),
array('comment_id' => $comment_id, 'user_id' => $user_id),
array('%s'), array('%d', '%d')
);
$change = $vote_type == 'helpful' ? 2 : -2;
}
} else {
// 新投票
$wpdb->insert($votes_table,
array(
'comment_id' => $comment_id,
'user_id' => $user_id,
'vote_type' => $vote_type
),
array('%d', '%d', '%s')
);
$change = $vote_type == 'helpful' ? 1 : -1;
}
// 更新评论的有用性计数
update_comment_helpful_count($comment_id);
wp_die(json_encode(array('success' => true, 'change' => $change)));
}
add_action('wp_ajax_helpful_vote', 'handle_helpful_vote_ajax');
add_action('wp_ajax_nopriv_helpful_vote', 'handle_helpful_vote_ajax');
// 更新评论有用性计数
function update_comment_helpful_count($comment_id) {
global $wpdb;
$votes_table = $wpdb->prefix . 'comment_votes';
$helpful_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $votes_table WHERE comment_id = %d AND vote_type = 'helpful'",
$comment_id
));
$unhelpful_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $votes_table WHERE comment_id = %d AND vote_type = 'unhelpful'",
$comment_id
));
update_comment_meta($comment_id, 'helpful_count', $helpful_count);
update_comment_meta($comment_id, 'unhelpful_count', $unhelpful_count);
}
3.2 创建用户贡献积分系统
// 用户贡献积分表
function create_user_contribution_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'user_contributions';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
contribution_id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) NOT NULL,
action_type varchar(50) NOT NULL,
points int(11) NOT NULL,
reference_id bigint(20),
contribution_date datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (contribution_id),
KEY user_id (user_id),
KEY action_type (action_type)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'create_user_contribution_table');
// 定义贡献行为与积分
function get_contribution_points($action_type) {
$points_map = array(
'post_comment' => 10,
'post_comment_with_image' => 15,
'post_comment_with_rating' => 12,
'ask_question' => 5,
'answer_question' => 20,
'helpful_vote_received' => 2,
'comment_featured' => 50,
'verified_purchase_comment' => 5
);
return isset($points_map[$action_type]) ? $points_map[$action_type] : 0;
}
// 记录用户贡献
function record_user_contribution($user_id, $action_type, $reference_id = null) {
global $wpdb;
$points = get_contribution_points($action_type);
if ($points > 0) {
$table_name = $wpdb->prefix . 'user_contributions';
$wpdb->insert($table_name,
array(
'user_id' => $user_id,
'action_type' => $action_type,
'points' => $points,
'reference_id' => $reference_id
),
array('%d', '%s', '%d', '%d')
);
// 更新用户总积分
update_user_total_points($user_id);
// 检查等级提升
check_user_level_up($user_id);
}
}
// 获取用户总积分
function get_user_total_points($user_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'user_contributions';
$total_points = $wpdb->get_var($wpdb->prepare(
"SELECT SUM(points) FROM $table_name WHERE user_id = %d",
$user_id
));
return $total_points ? intval($total_points) : 0;
}
// 更新用户总积分
function update_user_total_points($user_id) {
$total_points = get_user_total_points($user_id);
update_user_meta($user_id, 'total_contribution_points', $total_points);
}
// 用户等级系统
function get_user_level($points) {
$levels = array(
0 => '新手',
100 => '活跃用户',
500 => '核心贡献者',
1000 => '社区专家',
5000 => '顶级达人'
);
$user_level = '新手';
foreach ($levels as $required_points => $level_name) {
if ($points >= $required_points) {
$user_level = $level_name;
} else {
break;
}
}
return $user_level;
}
// 检查等级提升
function check_user_level_up($user_id) {
$points = get_user_total_points($user_id);
$current_level = get_user_meta($user_id, 'user_level', true);
$new_level = get_user_level($points);
if ($current_level != $new_level) {
update_user_meta($user_id, 'user_level', $new_level);
// 发送等级提升通知
send_level_up_notification($user_id, $current_level, $new_level);
}
}
3.3 实现评论排序与过滤功能
// 评论排序选项
function add_comment_sorting_options() {
if (is_singular('product')) {
echo '<div class="comment-sorting-options">
<label>排序方式:</label>
<select id="comment-sort">
<option value="newest">最新评论</option>
<option value="helpful">最有帮助</option>
<option value="highest_rating">评分最高</option>
<option value="lowest_rating">评分最低</option>
<option value="with_images">带图评论</option>
<option value="verified">已验证购买</option>
</select>
</div>';
}
}
add_action('comments_template_before', 'add_comment_sorting_options');
// AJAX评论排序
function get_sorted_comments_ajax() {
check_ajax_referer('comments_nonce', 'security');
$post_id = intval($_POST['post_id']);
$sort_by = sanitize_text_field($_POST['sort_by']);
$page = intval($_POST['page']);
$comments_per_page = get_option('comments_per_page', 10);
$args = array(
'post_id' => $post_id,
'status' => 'approve',
'number' => $comments_per_page,
'offset' => ($page - 1) * $comments_per_page
);
// 根据排序方式调整查询
switch ($sort_by) {
case 'helpful':
$args['meta_key'] = 'helpful_count';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
break;
case 'highest_rating':
$args['meta_key'] = 'rating';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
break;
case 'lowest_rating':
$args['meta_key'] = 'rating';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';
break;
case 'newest':
default:
$args['orderby'] = 'comment_date_gmt';
$args['order'] = 'DESC';
break;
}
$comments = get_comments($args);
// 特殊过滤处理
if ($sort_by == 'with_images') {
$comments = array_filter($comments, function($comment) {
$images = get_comment_meta($comment->comment_ID, 'comment_images', true);
return !empty($images);
});
} elseif ($sort_by == 'verified') {
$comments = array_filter($comments, function($comment) {
$verified = get_comment_meta($comment->comment_ID, 'is_verified_purchase', true);
return $verified == 1;
});
}
// 生成评论HTML
ob_start();
foreach ($comments as $comment) {
display_comment_item($comment);
}
$comments_html = ob_get_clean();
wp_die(json_encode(array(
'success' => true,
'html' => $comments_html,
'has_more' => count($comments) == $comments_per_page
)));
}
add_action('wp_ajax_get_sorted_comments', 'get_sorted_comments_ajax');
add_action('wp_ajax_nopriv_get_sorted_comments', 'get_sorted_comments_ajax');
// 评论过滤功能
function add_comment_filters() {
if (is_singular('product')) {
echo '<div class="comment-filters">
<label>筛选:</label>
<div class="filter-options">
<label><input type="checkbox" name="filter_rating[]" value="5"> 5星</label>
<label><input type="checkbox" name="filter_rating[]" value="4"> 4星</label>
<label><input type="checkbox" name="filter_rating[]" value="3"> 3星</label>
<label><input type="checkbox" name="filter_rating[]" value="2"> 2星</label>
<label><input type="checkbox" name="filter_rating[]" value="1"> 1星</label>
<label><input type="checkbox" name="filter_verified" value="1"> 已验证购买</label>
<label><input type="checkbox" name="filter_with_images" value="1"> 带图评论</label>
</div>
<button id="apply-filters">应用筛选</button>
<button id="reset-filters">重置</button>
</div>';
}
}
add_action('comments_template_before', 'add_comment_filters');
前端交互与用户体验优化
4.1 响应式评论与问答界面
/* 评论与问答系统CSS */
.product-reviews-section {
margin: 40px 0;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
}
.comment-item, .qa-item {
padding: 20px;
margin-bottom: 20px;
background: white;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.rating-stars {
display: inline-block;
unicode-bidi: bidi-override;
direction: rtl;
}
.rating-stars input {
display: none;
}
.rating-stars label {
color: #ddd;
font-size: 24px;
padding: 0 2px;
cursor: pointer;
}
.rating-stars input:checked ~ label,
.rating-stars label:hover,
.rating-stars label:hover ~ label {
color: #ffd700;
}
.comment-images {
display: flex;
gap: 10px;
margin-top: 10px;
flex-wrap: wrap;
}
.comment-image {
width: 100px;
height: 100px;
object-fit: cover;
border-radius: 4px;
cursor: pointer;
}
.helpful-vote {
margin-top: 10px;
}
.helpful-btn, .unhelpful-btn {
padding: 5px 15px;
margin-right: 10px;
border: 1px solid #ddd;
background: white;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s;
}
.helpful-btn:hover, .unhelpful-btn:hover {
background: #f0f0f0;
}
.helpful-btn.active {
background: #4CAF50;
color: white;
border-color: #4CAF50;
}
.unhelpful-btn.active {
background: #f44336;
color: white;
border-color: #f44336;
}
/* 问答系统样式 */
.qa-form textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
resize: vertical;
}
.similar-questions {
background: #e8f4fd;
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
}
.similar-questions ul {
list-style: none;
padding-left: 0;
}
.similar-questions li {
padding: 10px;
border-bottom: 1px solid #d1e7f7;
}
.similar-questions li:last-child {
border-bottom: none;
}
/* 移动端适配 */
@media (max-width: 768px) {
.comment-images {
justify-content: center;
}
.comment-image {
width: 80px;
height: 80px;
}
.filter-options {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.comment-sorting-options,
.comment-filters {
flex-direction: column;
align-items: flex-start;
}
.comment-sorting-options select,
.comment-filters .filter-options {
width: 100%;
margin-top: 10px;
}
}
4.2 AJAX交互与实时更新
// 评论投票功能
jQuery(document).ready(function($) {
// 评论有用性投票
$('.helpful-btn, .unhelpful-btn').on('click', function(e) {
e.preventDefault();
if (!is_user_logged_in) {
alert('请先登录后再投票');
return;
}
var button = $(this);
var commentId = button.data('comment-id');
var voteType = button.hasClass('helpful-btn') ? 'helpful' : 'unhelpful';
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'helpful_vote',
comment_id: commentId,
vote_type: voteType,
security: vote_nonce
},
beforeSend: function() {
button.prop('disabled', true).text('投票中...');
},
success: function(response) {
if (response.success) {
var countElement = button.find('.count');
var currentCount = parseInt(countElement.text());
countElement.text(currentCount + response.change);
// 更新按钮状态
$('.vote-btn').removeClass('active');
button.addClass('active');
// 记录用户贡献
if (response.change > 0) {
recordContribution('helpful_vote_given', commentId);
}
}
},
complete: function() {
button.prop('disabled', false);
}
});
});
// 评论排序
$('#comment-sort').on('change', function() {
var sortBy = $(this).val();
var postId = $('#post-id').val();
loadSortedComments(postId, sortBy, 1);
});
// 评论筛选
$('#apply-filters').on('click', function() {
var filters = {
ratings: [],
verified: false,
withImages: false
};
$('input[name="filter_rating[]"]:checked').each(function() {
filters.ratings.push($(this).val());
});
filters.verified = $('input[name="filter_verified"]').is(':checked');
filters.withImages = $('input[name="filter_with_images"]').is(':checked');
applyCommentFilters(filters);
});
// 问答提交
$('#qa-form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: ajaxurl,
type: 'POST',
data: formData + '&action=submit_question',
beforeSend: function() {
$('#qa-form button').prop('disabled', true).text('提交中...');
},
success: function(response) {
if (response.success) {
$('#qa-form')[0].reset();
$('#qa-form').before('<div class="success-message">问题已提交!</div>');
// 记录用户贡献
recordContribution('ask_question', response.question_id);
// 显示相似问题
if (response.similar_questions) {
displaySimilarQuestions(response.similar_questions);
}
}
},
complete: function() {
$('#qa-form button').prop('disabled', false).text('提交问题');
}
});
});
// 加载更多评论
$('#load-more-comments').on('click', function() {
var page = $(this).data('page') || 2;
var sortBy = $('#comment-sort').val();
var postId = $('#post-id').val();
loadSortedComments(postId, sortBy, page);
});
// 图片上传预览
$('#comment_images').on('change', function(e) {
var files = e.target.files;
var preview = $('#image-preview');
preview.empty();
for (var i = 0; i < Math.min(files.length, 3); i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = function(e) {
var img = $('<img>').attr({
'src': e.target.result,
'class': 'upload-preview'
});
preview.append(img);
}
reader.readAsDataURL(file);
}
});
});
// 加载排序后的评论
function loadSortedComments(postId, sortBy, page) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'get_sorted_comments',
post_id: postId,
sort_by: sortBy,
page: page,
security: comments_nonce
},
beforeSend: function() {
$('#comments-list').addClass('loading');
},
success: function(response) {
if (response.success) {
if (page == 1) {
$('#comments-list').html(response.html);
} else {
$('#comments-list').append(response.html);
}
// 更新加载更多按钮
