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

WooCommerce短码改造:仅显示用户未评价的已购商品

改造后的短码代码
add_shortcode( 'customer_products', 'rrr_products_current_user' );
 
function rrr_products_current_user() {
    // 检查用户是否登录
    if ( ! is_user_logged_in() ) {
        return '<p>请先登录查看您的未评价商品</p>';
    }
 
    // 获取当前用户已支付的订单
    $customer_orders = get_posts( array(
        'posts_per_page' => -1,
        'meta_key'       => '_customer_user',
        'meta_value'     => get_current_user_id(),
        'post_type'      => wc_get_order_types(),
        'post_status'    => array_keys( wc_get_is_paid_statuses() ),
    ) );
 
    // 无订单时返回提示
    if ( ! $customer_orders ) {
        return '<p>您暂无已支付订单</p>';
    }
 
    // 收集所有已购商品ID
    $ids = array();
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order->ID );
        $items = $order->get_items();
        foreach ( $items as $item ) {
            $ids[] = $item->get_product_id();
        }
    }
 
    // 去重商品ID
    $unique_ids = array_unique( $ids );
    $current_user_id = get_current_user_id();
    $unreviewed_product_ids = array();
 
    // 过滤掉已评价的商品
    foreach ( $unique_ids as $product_id ) {
        // 使用has_reviewed_product判断用户是否评价过该商品
        if ( ! has_reviewed_product( $product_id, $current_user_id ) ) {
            $unreviewed_product_ids[] = $product_id;
        }
    }
 
    // 无未评价商品时返回提示
    if ( empty( $unreviewed_product_ids ) ) {
        return '<p>您已完成所有已购商品的评价</p>';
    }
 
    // 构建未评价商品的HTML输出
    $output = '<div class="unreviewed-products-container">';
    foreach ( $unreviewed_product_ids as $product_id ) {
        $product = wc_get_product( $product_id );
        if ( ! $product ) continue;
 
        $output .= '<div class="unreviewed-product-item">';
        // 商品图片
        $output .= '<a href="' . esc_url( $product->get_permalink() ) . '" class="product-image">';
        $output .= $product->get_image( 'woocommerce_thumbnail' );
        $output .= '</a>';
        // 商品名称与链接
        $output .= '<h3 class="product-title"><a href="' . esc_url( $product->get_permalink() ) . '">' . esc_html( $product->get_name() ) . '</a></h3>';
        // 评价提示
        $output .= '<p class="review-prompt">*请对该商品发表评价*</p>';
        $output .= '</div>';
    }
    $output .= '</div>';
 
    return $output;
}

关键修改说明

  • 过滤已评价商品:在收集并去重商品ID后,通过has_reviewed_product($product_id, $current_user_id)判断用户是否已评价该商品,只保留未评价的商品ID。这个函数是WooCommerce内置函数,专门用于检查指定用户对指定商品是否有评价记录。

  • 自定义HTML输出:放弃原代码中调用[products]短码的方式,改为手动构建HTML结构,这样可以灵活添加“请对该商品发表评价”的提示文本,同时能更精准控制商品展示的样式。

  • 安全输出处理:使用esc_url()、esc_html()等WordPress安全函数处理输出内容,避免XSS漏洞,确保代码的安全性。

  • 完善提示信息:针对用户未登录、无订单、无未评价商品三种情况,分别添加了友好的提示文本,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:50:06