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

如何设置Woocommerce仅订单完成用户可查看对应产品图库

推荐解决方案

优先选择调整权限判断逻辑的方案,不推荐自动删除未支付订单:删除订单会丢失交易记录,既不利于后续对账、故障排查,也无法为用户展示历史支付失败订单引导二次支付,存在运营层面的缺陷。

具体代码修改

替换你原来的判断逻辑即可,新逻辑会仅校验用户已完成订单中是否包含当前商品,排除pending、failed、cancelled等状态的无效订单:

global $post, $product;
$current_user = wp_get_current_user();
$allowed_roles = array('administrator');
$has_permission = false;

// 管理员直接放行
if (array_intersect($allowed_roles, $current_user->roles)) {
    $has_permission = true;
} elseif ($current_user->ID > 0) {
    // 查询当前用户所有已完成的订单
    $customer_orders = wc_get_orders(array(
        'customer_id' => $current_user->ID,
        'status' => array('completed'), // 可根据需求增加processing状态
        'limit' => -1,
        'return' => 'ids'
    ));

    if (!empty($customer_orders)) {
        foreach ($customer_orders as $order_id) {
            $order = wc_get_order($order_id);
            // 遍历订单商品判断是否存在当前商品
            foreach ($order->get_items() as $item) {
                if ($item->get_product_id() == $product->get_id()) {
                    $has_permission = true;
                    break 2; // 匹配到直接跳出两层循环
                }
            }
        }
    }
}

if ($has_permission) { 
    /* 原来渲染产品图库的代码 */
}

可选优化(针对虚拟数字产品)

如果你的所有商品都是虚拟数字类,可添加下方代码实现付款成功后自动将订单状态设置为已完成,无需手动审核:

add_action('woocommerce_payment_complete', 'auto_complete_virtual_order');
function auto_complete_virtual_order($order_id) {
    if (!$order_id) return;
    $order = wc_get_order($order_id);
    
    $is_virtual = true;
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if (!$product->is_virtual()) {
            $is_virtual = false;
            break;
        }
    }
    
    if ($is_virtual) {
        $order->update_status('completed');
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:54:05