隐藏 Woocommerce 中特定用户角色的特定运输方式

Hide specific shipping methods for a specific user roles in Woocommerce

在 Woocommerce 中,我使用 WooCommerce Wholesale Pro Suite (来自 IgniteWoo) 和 Flat Rate Box Shipping 插件将 B2B 添加到我们的网店。

我正在尝试为特定用户角色、来宾和客户禁用统一费率盒装运输。我在网上搜索后找到了这段代码:

add_filter( 'woocommerce_package_rates', 'hide_shipping_for_user_role', 10, 2 );
function hide_shipping_for_user_role( $rates, $package ) {
// Role ID to be excluded
$excluded_role = "wholesale_customer";

// Shipping rate to be excluded
$shipping_id = 'table_rate_shipping_free-shipping';

// Get current user's role
$user = wp_get_current_user();
if ( empty( $user ) ) return false;

if( in_array( $excluded_role, (array) $user->roles ) && isset( $rates[ $shipping_id ] ) )
unset( $rates[ $shipping_id ] );

return $rates;
}

我应该用什么来代替“wholesale_customer”和“table_rate_shipping_free-shipping”,这样对于来宾和客户角色,统一邮资箱运输不会显示?

感谢任何帮助。

更新二:

You may have to "Enable debug mode" in general shipping settings under "Shipping options" tab, to disable temporarily shipping caches.

详情: "Flat rate boxes" 的送货方式 ID 是 flat_rate_boxes

以下代码将为 "Guests" (未登录用户) 和 "customer" 用户角色禁用 "Flat rate boxes" 运输方式:

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

    ## --- Your settings --- ##
    $excluded_role = "customer"; // User role to be excluded
    $shipping_id = 'flat_rate_boxes'; // Shipping rate to be removed

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

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

Don't forget to enable back shipping cache.