Skip to content

Instantly share code, notes, and snippets.

@renjith-ph
Last active December 10, 2019 14:37
Show Gist options
  • Save renjith-ph/e72e111a31ffb8b2e52742dd5c374d37 to your computer and use it in GitHub Desktop.
Save renjith-ph/e72e111a31ffb8b2e52742dd5c374d37 to your computer and use it in GitHub Desktop.
Snippet to hide the woocommerce shipping methods based on user role
/**
* Title : Snippet to hide the woocommerce shipping methods based on user role .
* Created at : 08 March 2019
* Updated at : 08 March 2019
* Pluginhive Plugins : https://www.pluginhive.com/
* Gist Link : https://gist.github.com/renjith-ph/e72e111a31ffb8b2e52742dd5c374d37/
*/
add_filter( 'woocommerce_package_rates', function( $shipping_rates ) {
// Provide user role and shipping methods values pair
$role_shipping_method_arr = array(
'customer' => array( 'free_shipping:2'),
'administrator' => array( 'flat_rate:1',),
'guest' => array('wf_shipping_ups:96'),
);
$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) || (empty($current_user->roles) && $role=='guest') ) {
// 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;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment