Skip to content

Instantly share code, notes, and snippets.

@saranyagokula
Created April 5, 2024 16:22
Show Gist options
  • Save saranyagokula/4293a134c199f40f13845790734489e6 to your computer and use it in GitHub Desktop.
Save saranyagokula/4293a134c199f40f13845790734489e6 to your computer and use it in GitHub Desktop.
hide shipping methods for guest users and subscribers
add_filter( 'woocommerce_package_rates', 'ts_hide_specific_shipping_method', 10, 2 );
function ts_hide_specific_shipping_method( $rates, $package ) {
// Define the shipping rate IDs to hide for guests
$targeted_rate_ids_guest = array(
'flat_rate:4', // Flat rate shipping method for guests
// Free shipping method for guests
);
// Define the shipping rate IDs to hide for subscribers
$targeted_rate_ids_subscriber = array(
'free_shipping:5' // Add the shipping rate IDs to hide for subscribers here
);
// Check if user is not logged in (guest user)
if ( ! is_user_logged_in() ) {
// If user is not logged in, hide specific shipping methods for guests
foreach ( $targeted_rate_ids_guest as $rate_id ) {
if ( isset( $rates[ $rate_id ] ) ) {
unset( $rates[ $rate_id ] );
}
}
} else {
// If user is logged in, check if the user is a subscriber
$user = wp_get_current_user();
if ( in_array( 'subscriber', (array) $user->roles ) ) {
// If user is a subscriber, hide specific shipping methods for subscribers
foreach ( $targeted_rate_ids_subscriber as $rate_id ) {
if ( isset( $rates[ $rate_id ] ) ) {
unset( $rates[ $rate_id ] );
}
}
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment