如何修改Woocommerce代码让变体商品显示未评价提示?
修复WooCommerce变体商品评价提示不显示问题
原代码仅能为已购买未评价的简单商品显示评价提示,但用户购买变体商品(如多尺码T恤的特定尺码)后,进入商品详情页无法看到提示,切换默认尺码也无效。以下是修改后的完整代码,可同时支持简单商品和变体商品:
// 检查用户是否已对商品发表评价 function has_reviewed_product( $product_id ) { global $wpdb; $user = wp_get_current_user(); if( $user->ID == 0 ) return false; // 如果是变体商品,获取父商品ID(WooCommerce评论默认关联父商品) $product = wc_get_product($product_id); if ( $product && $product->is_type('variation') ) { $product_id = $product->get_parent_id(); } // 统计用户已审核的商品评论数,避免SQL注入 $count = $wpdb->get_var( $wpdb->prepare(" SELECT COUNT(comment_ID) FROM {$wpdb->prefix}comments WHERE comment_post_ID = %d AND comment_author_email = %s AND comment_type = 'review' AND comment_approved = '1' ", $product_id, $user->user_email) ); return $count > 0; } // 检查用户是否已购买商品(仅统计已完成状态的订单) function customer_has_bought_product( $product_id, $user_id = 0 ) { global $wpdb; $customer_id = $user_id == 0 || $user_id == '' ? get_current_user_id() : $user_id; $status = 'wc-completed'; if( ! $customer_id ) return false; // 统计用户已购买的商品数量,避免SQL注入 $count = $wpdb->get_var( $wpdb->prepare(" SELECT COUNT(woim.meta_value) FROM {$wpdb->prefix}posts AS p INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id WHERE p.post_status = %s AND pm.meta_key = '_customer_user' AND pm.meta_value = %d AND woim.meta_key IN ( '_product_id', '_variation_id' ) AND woim.meta_value = %d ", $status, $customer_id, $product_id) ); return $count > 0; } add_action( 'woocommerce_before_single_product_summary', 'woo_review_discount_message'); function woo_review_discount_message() { global $product; $current_user = wp_get_current_user(); if ( $current_user->ID === 0 ) return; // 未登录用户不显示提示 // 处理商品类型:变体商品取父ID,其他取当前商品ID $target_product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); // 检查用户是否购买过该商品/变体,且未评价过对应的父商品 $has_bought = customer_has_bought_product($product->get_id()); $has_reviewed = has_reviewed_product($target_product_id); if ( $has_bought && !$has_reviewed ) { // 输出评价提示,修复原代码多余的</a>标签 echo '<div class="user-bought"><span style="color:#CA364D;font-weight:bold;font-size:18px;"><i class="wishlist-icon icon-heart-o"></i></span> Hi ' . esc_html($current_user->first_name) . '! Please write a review below.</div>'; } }
修改说明:
- 移除变体商品限制:删除原代码中
! $product->is_type('variable')的判断,允许变体商品页面触发提示逻辑。 - 适配变体评论逻辑:WooCommerce中变体商品的评论默认关联父商品,因此检查评价时自动切换为父商品ID进行查询。
- 修复SQL注入风险:使用
$wpdb->prepare()对数据库查询参数进行转义,提升代码安全性。 - 修复HTML错误:移除原代码中多余的
</a>标签,避免页面结构混乱。 - 优化用户判断:提前判断未登录用户,直接终止逻辑减少无效计算。
内容的提问来源于stack exchange,提问作者Lgane
相关产品推荐
相关产品推荐

