Php 基于用户角色的电子商务配送方法

Php 基于用户角色的电子商务配送方法,php,wordpress,woocommerce,user-roles,shipping-method,Php,Wordpress,Woocommerce,User Roles,Shipping Method,我想根据用户角色启用或禁用装运方法。 我已经测试了各种不同的代码和方法,到目前为止没有一种有效 当前代码:(源代码:) (也测试了原始代码段,未做任何更改,接受用户角色) 不适合我。我也用“local_Pick”对它进行了测试,它有时确实能工作,但似乎对浏览器缓存和会话非常敏感。我还需要的是3个方法,它们以相同的名称调用,但子编号将它们分开:shipmondo:3,shipmondo:4,等等(在“值”下的浏览器检查中找到),还有一个叫做ID的东西,看起来像:“shipping\u method

我想根据用户角色启用或禁用装运方法。 我已经测试了各种不同的代码和方法,到目前为止没有一种有效

当前代码:(源代码:)

(也测试了原始代码段,未做任何更改,接受用户角色) 不适合我。我也用“local_Pick”对它进行了测试,它有时确实能工作,但似乎对浏览器缓存和会话非常敏感。我还需要的是3个方法,它们以相同的名称调用,但子编号将它们分开:shipmondo:3,shipmondo:4,等等(在“值”下的浏览器检查中找到),还有一个叫做ID的东西,看起来像:“shipping\u method\u 0\u shipmondo3”不知道我是否可以使用它,但这有点难以理解,当代码更新不正确时。这个片段来自2018年,因此可能是过时的东西,但我发现的更新片段基于相同的原则,看起来没有太大的不同

另外,为什么需要“| |!用户是否已登录?”?我只需要禁用批发用户的3个方法中的2个,不需要影响任何其他角色,也不需要来宾。我们已经为此奋斗了好几天了

还有,关于强制Wordpress和Woocommerce更新,而不是在缓存中四处游荡,有什么建议吗


提前感谢。

您混淆了运输方法“方法Id”和运输方法“费率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    = 'shipmondo:3'; // The shipping rate ID to hide
    $targeted_user_roles = array('b2b');  // 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;
}
代码进入活动子主题(或活动主题)的functions.php文件。它应该会起作用


不要忘记清空购物车,以清除配送缓存数据。

Hmm,此代码段关闭所有配送方法。。。??顺便说一句,您可能需要在“unset”行中添加分号;)但至少它正在做一些事情。非常感谢。奇怪。我会做进一步的测试。对我来说,用户角色b2b没有可用的配送方法,而其他所有角色都有3个。我不知道为什么,但这段代码不适合我。当我设置此代码时,所有用户的所有配送方法都消失了。所以它打破了运输方式(对我来说)。@Pandusen更新了代码:这次它会起作用(先清空你的购物车)。Thanx。真管用!我修改了它,为b2b隐藏了2种方法,为其他人隐藏了1种方法,这样b2b就有了自己的发货方法。它工作得很好,看起来像岩石一样坚固。看来大部分的怪事都来自“当前用户”
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    = 'shipmondo:3'; // The shipping rate ID to hide
    $targeted_user_roles = array('b2b');  // 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;
}