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

求助:基于WordPress用户角色移除自提配送选项的代码无效

WordPress WooCommerce 隐藏自提选项失效排查与修复

问题描述

我在WordPress电商站点中设置了三类用户角色:administrator、local_pickup_customer和customer,希望访客及customer角色用户在结账时无法看到Local Pickup(自提)选项。尝试多段代码后,编写并修改了以下逻辑:若用户角色不属于administrator或local_pickup_customer,则移除自提选项。已确认rate_id正确且清理了浏览器及购物车缓存,但自提选项仍未消失,请问问题出在哪里?

用户提供的代码:

add_filter( 'woocommerce_package_rates', 'hide_specific_shipping_method_based_on_user_role', 100, 2 );
function hide_specific_shipping_method_based_on_user_role( $rates, $package ) {
    // Here define the shipping rate ID to hide
    $targeted_rate_id    = 'local_pickup:2'; // The shipping rate ID to hide
    $targeted_user_roles = array('administrator', 'local_pickup_customer');  // The user roles to target (array)

    $current_user  = wp_get_current_user();
    $matched_roles = array_intersect($targeted_user_roles, $current_user->roles);

    if( empty($matched_roles) && isset($rates[$targeted_rate_id]) ) {
        unset($rates[$targeted_rate_id]);
    }
    return $rates;
}

rate_id验证截图:
rate_id截图

问题排查与修复

你的代码存在两个关键问题:

  • 访客场景处理不严谨:未登录访客的wp_get_current_user()返回对象无roles属性,虽然逻辑上array_intersect会返回空,但WooCommerce的运输钩子在访客模式下可能因缓存或优先级问题未触发预期逻辑。
  • 缓存未彻底清除:仅清理浏览器和购物车缓存不够,WooCommerce运输方式有独立缓存,需要强制刷新。

修复后的代码:

add_filter( 'woocommerce_package_rates', 'hide_local_pickup_for_non_authorized_users', 9999, 2 );
function hide_local_pickup_for_non_authorized_users( $rates, $package ) {
    $targeted_rate_id    = 'local_pickup:2';
    $allowed_roles       = array('administrator', 'local_pickup_customer');
    $current_user        = wp_get_current_user();
    $is_user_authorized  = false;

    // 验证登录用户权限
    if ( is_user_logged_in() ) {
        $is_user_authorized = !empty(array_intersect($allowed_roles, $current_user->roles));
    }

    // 访客或未授权用户移除自提选项
    if ( !$is_user_authorized && isset($rates[$targeted_rate_id]) ) {
        unset($rates[$targeted_rate_id]);
    }

    // 强制刷新运输方式缓存
    foreach ( $rates as $rate_key => $rate ) {
        $rates[$rate_key]->cost = $rate->cost;
    }

    return $rates;
}

后续操作步骤

  1. 将修复后的代码替换原有代码,保存到主题的functions.php文件或自定义插件中。
  2. 进入WooCommerce后台「设置」→「运输」→「运输区域」,编辑包含自提选项的运输区域,点击保存按钮强制刷新缓存。
  3. 分别测试访客模式和customer角色登录模式,确认自提选项已隐藏。

内容的提问来源于stack exchange,提问作者Mr. Victor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:03:11