Need help removing a shipping rate based on WordPress user roles. Nothing is working!

[ad_1]

I’m trying to set up a shipping rate 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_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’ve been working on this for hours and I’m going crazy! I’m starting to suspect that there must be something else going on that is causing this not to work. I’m not sure what it could be though.

[ad_2]
1 Comment
  1. I think this just hides the rates, not the options?

    Been a while since I touched WooCommerce code like this, so I could be wrong.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer