Reputation: 11
I've scoured this site and others trying to find code I can put into my functions.php file so that certain users/guests can't see the Local Pickup option at checkout. I have 3 user roles on my store: administrator, local_pickup_customer, and customer. When a guest or customer is checking out, I want Local Pickup to be unset. After trying countless pieces of code, I settled on and edited the code below as it seemed the most logical to me. Instead of looking for customer and guest to remove local pickup (which seemed trickier with the guest aspect), I like removing local pickup if user role was not administrator or local_pickup_customer.
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 = 'local_pickup:2'; // The shipping rate ID to hide
$targeted_user_roles = array('administrator', 'local_pickup_customer'); // 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;
}
I've been working on this for hours and I'm going crazy. I made sure that I had the correct rate_id (ran some debug code to get it). I made sure to clear browser and cart cache when I made any changes. The local pickup option will just not go away for customer or guest. What am I doing wrong?
Upvotes: 1
Views: 38
Reputation: 945
I would recommend looping through the rates and using a more specific match (using method_id
) to determine whether or not to unset
. You could use this method to efficiently unset multiple if you needed to. Something like:
add_filter( 'woocommerce_package_rates', 'hide_local_pickup_for_users', 10, 2 );
function hide_local_pickup_for_users( $rates, $package ) {
$targeted_rate_id = 'local_pickup';
$targeted_user_roles = array('administrator', 'local_pickup_customer');
$current_user = wp_get_current_user();
$matched_roles = array_intersect($targeted_user_roles, $current_user->roles);
if ( empty($matched_roles) ) {
foreach( $rates as $rate_key => $rate ) {
if ( $rate->method_id === $targeted_rate_id ) {
unset($rates[$rate_key]);
}
}
}
return $rates;
}
I would also set the priority to 10 instead of 100, as shown in my example.
Upvotes: 0