Hide Woocommerce Shipping Methods Based on User Role

The ELEX shipping plugins do not have the option to hide/show shipping methods based on the user roles within the plugin settings. However, our developers have found a solution to achieve this using a code snippet. You can use the below code snippet to achieve this.

add_filter( 'woocommerce_package_rates', function( $shipping_rates ) {
// Provide user role and shipping method ID you want to hide for the user role.
$role_shipping_method_arr = array(
'customer' 			=>	array( 'free_shipping:2'),
'administrator'		=>	array( 'wf_dhl_shipping'),
);
$current_user = wp_get_current_user();
// 	Uncomment below lines to get current user roles and check in Woocommerce->status->Log ,file name will contain xa_current_user_role
//	$log = new WC_Logger();
//	$log->add('xa_current_user_role', print_r($current_user->roles,true));
// Loop through the user role and shipping method pair
foreach( $role_shipping_method_arr as $role => $shipping_methods_to_hide ) {
// Check if defined role exist in current user role or not
if( in_array( $role, $current_user->roles) ) {
// Loop through all the shipping rates
foreach( $shipping_rates as $shipping_method_key => $shipping_method ) {
$shipping_id = $shipping_method->get_id();
// Unset the shipping method if found
if( in_array( $shipping_id, $shipping_methods_to_hide) ) {
unset($shipping_rates[$shipping_method_key]);
}
}
}
}
return $shipping_rates;
} );

Now according to the above code snippet the DHL option will be hidden for the ‘admin’ user role, and for the ‘customer’ role, the free shipping option will be hidden.

How will I know the Shipping ID I need to enter?

To get the shipping ID of the services, showing in the cart or checkout page, you can right click the shipping option in the Cart page and select Inspect. And in the console that shows up, the element details will be already selected so you can see the shipping ID under “value”. This you can copy and enter the same in the Show Hide shipping code snippet in the shipping ID field.
Hope this article helped with your business requirement. If you need help setting up a plugin and the code snippet, you can always contact our team.

    Leave a Reply