如何解决基于用户角色的 Woocommerce Shipping 方法
我想根据用户角色启用或禁用送货方式。 我测试了各种不同的代码和方法,但到目前为止都没有奏效。
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”对其进行了测试,它有时确实有效,但似乎对浏览器缓存和会话非常敏感。另外我需要的是 3 个方法,它们以相同的名称调用,但用一个子编号将它们分开:shipmondo:3、shipmondo:4 等(在浏览器检查中的“值”下找到)还有一个叫做 ID 的东西,看起来像: 'shipping_method_0_shipmondo3' 不知道我是否可以用它来代替,但是当代码没有正确更新时,很难弄清楚。该代码段来自 2018 年,因此它可能是过时的东西,但我发现的较新的代码段基于相同的原则,并且看起来并没有太大不同。
另外,为什么需要“|| !is_user_logged_in()”?我只需要为批发用户禁用 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 文件中。它应该可以工作。
不要忘记清空您的购物车,以清除运输缓存数据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。