I have been looking at lots of snippets to enable a shipping method for a specific user role only. So anyone who is NOT part of this user role should not see it, including guests who are not logged in.
The snippets like below don't achieve this and I am struggling to reverse the logic. I want to avoid having to manually input every shipping method to the snippet, which is obviously not future proof due to when new shipping methods are added.
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;
}
Original Post: Woocommerce Shipping method based on user role
Author: LoicTheAztec