[英]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.