仅在 WooCommerce 中为特定用户角色启用送货方式

Enable shipping method for specific user role ONLY in WooCommerce

我一直在查看大量片段以仅针对特定用户角色启用送货方式。因此,任何不属于此用户角色的人都不应看到它,包括未登录的来宾。

像下面这样的代码片段没有实现这一点,我正在努力扭转逻辑。我想避免必须手动将每种运输方式输入到代码段,这显然不是未来的证据,因为添加了新的运输方式。

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    = '15'; // The shipping rate ID to hide
    $targeted_user_roles = array('clubadmin');  // 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;
}

原文Post:

作者:LoicTheAztec

默认情况下,应禁用此送货方式,除非用户履行特定用户角色

$rate_ids 数组中,您为相应的送货方式添加 1 个或多个 ID

所以你得到:

function filter_woocommerce_package_rates( $rates, $package ) {
    // Set the rate IDs in the array
    $rate_ids = array( 'local_pickup:1', 'free_shipping:2' );
    
    // NOT the required user role, remove shipping method(s)
    if ( ! current_user_can( 'administrator' ) ) {
        // Loop trough
        foreach ( $rates as $rate_id => $rate ) {
            // Checks if a value exists in an array
            if ( in_array( $rate_id, $rate_ids ) ) {
                unset( $rates[$rate_id] );
            }
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

注意: 要找到正确的 $rate_ids 您可以使用此 的第二部分 -(“用于调试目的”部分)