You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WooCommerce产品页仅展示当前用户的评论?

实现WooCommerce产品页仅显示当前用户评论的方法

你之前修改的review.php是单个产品评论的渲染模板,仅负责展示单条评论的结构,无法控制哪些评论被加载。要实现仅显示当前用户的产品评论,需要从评论查询的源头入手,以下是两种可行方案:

方案一:修改评论列表模板(直接修改文件)

找到WooCommerce模板文件woocommerce/templates/single-product/reviews.php(注意是复数的reviews.php,不是你之前修改的单个评论模板),替换其中的评论查询逻辑:

原文件中类似这样的代码:

$comments = get_comments( apply_filters( 'woocommerce_product_review_query', array(
    'post_id' => $product_id,
    'status'  => 'approve',
    'order'   => $order,
) ) );

替换为:

$current_user_id = get_current_user_id();
$comments = get_comments( apply_filters( 'woocommerce_product_review_query', array(
    'post_id' => $product_id,
    'status'  => 'approve',
    'order'   => $order,
    'user_id' => $current_user_id, // 添加这行,过滤当前用户的评论
) ) );

修改后,产品页只会加载当前登录用户的已审核评论。

方案二:使用钩子过滤(推荐,无需修改模板)

在主题的functions.php文件中添加以下代码,通过woocommerce_product_review_query钩子过滤评论查询参数:

add_filter( 'woocommerce_product_review_query', 'filter_product_reviews_to_current_user' );
function filter_product_reviews_to_current_user( $query_args ) {
    // 仅在用户登录时生效
    if ( is_user_logged_in() ) {
        $query_args['user_id'] = get_current_user_id();
    }
    return $query_args;
}

这种方法无需修改WooCommerce核心模板,避免后续插件更新覆盖你的修改,更安全稳定。

注意:如果用户未登录,方案二会保持默认逻辑显示所有评论;若需要未登录时隐藏所有评论,可在函数内添加判断,未登录时返回空数组或调整查询参数。

内容的提问来源于stack exchange,提问作者Andrey Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:41:04