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
CodePudding user response:
By default, this shipping method should be disabled, unless the user fulfills a certain user role
In the $rate_ids
array you add 1 or more IDs for the respective shipping methods
So you get:
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 );
Note: to find the correct $rate_ids
you can use the second part from this answer - (The "for debugging purposes" part)