How hide a specific shipping method for all user groups except one in woocommerce

29 views Asked by At

On our webshop we want to use certain user groups to have benefits and one of them is to have a 50% discount on the shipping method. So i made a shipping method which has 50% discount and used a PHP code that hides the regular shipping method for the user group "subscribers". The problem now is that i want to hide the 50% discount shipping method for the remaining visitors including 'guest' or people who arent asigned to any user group.

Based on Woocommerce Shipping method based on user role, here is my code:

add_filter( 'woocommerce_package_rates', 'ts_hide_specific_shipping_method_based_on_user_role', 100, 2 );
function ts_hide_specific_shipping_method_based_on_user_role( $rates, $package ) {
    // Here define the shipping rate ID to hide
    $targeted_rate_id    = 'flat_rate:1'; // The shipping rate ID to hide
    $targeted_user_roles = array( 'subscriber');  // 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;
}

The thing is that is solves half of my problem which is hiding the regular shipping method for subscribers, but now the 50% discount shipping method is being shown to all the other visitors. How can i solve this?

I already tried to adjust the user groups, but the main problem is the most of the visitors arent asigned to a user group, but i dont know how to target them in the code.

1

There are 1 answers

2
Lajos Arpad On

You will need an else branch and you will need to remove the appropriate item:

    if( ! empty($matched_roles) && isset($rates[$targeted_rate_id]) ) {
        unset($rates[$targeted_rate_id]);
    } else {
        unset($rates[$your_key_here]);
    }

In the above I've used $your_key_here because I lack information on what needs to be hidden from the rates in the other case. But you will need to either figure it out, or provide more information about what exactly you want to avoid showing.