繁体   English   中英

Woocommerce 基于用户角色的发货方式

[英]Woocommerce Shipping method based on user role

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

当前代码:(来源: stacklink

add_filter( 'woocommerce_package_rates', 'hide_specific_shipping_method_based_on_user_role', 30, 2 );
function hide_shipping_method_based_on_user_role( $rates, $package ) {

    $shipping_id = 'shipmondo:3';

    foreach( $rates as $rate_key => $rate ){
        if( $rate->method_id === $shipping_id ){
            if( current_user_can( 'b2b' ) || ! is_user_logged_in()){
                unset($rates[$rate_key]);
                break;
            }
        }
    }
    return $rates;
}

(也测试了原始片段,没有更改,接受用户角色)对我不起作用。 我也用'local_pickup'对其进行了测试,它有时确实有效,但似乎对浏览器缓存和 session 非常敏感。 我还需要的是 3 个方法,它们以相同的名称调用,但用一个子编号分隔它们:shipmondo:3、shipmondo:4 等(在“值”下的浏览器检查中找到)还有一个叫做 ID 的东西,它看起来像:'shipping_method_0_shipmondo3' 不知道我是否可以改用它,但是当代码没有正确更新时,很难弄清楚。 该片段来自 2018 年,因此它可能是一个过时的东西,但我发现的较新片段基于相同的原则,并且看起来并没有太大的不同。

另外,为什么需要“||?is_user_logged_in()”,我只需要为批发用户禁用 3 种方法中的 2 种,不需要影响任何其他角色。 也不是客人。 这几天一直在和这个作斗争。

此外,关于强制 Wordpress 和 Woocommerce 更新而不是在缓存中游动的任何建议?

提前致谢。

您混淆了运输方式“Method Id”和运输方式“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    = '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文件。 它应该工作。

不要忘记清空您的购物车,以清除运输缓存数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM