
How to exclude shipping methods by user role in WooCommerce
In many online stores, it’s useful to offer different shipping options depending on the user’s role. For example, you might want to hide Free Shipping for guest users, or offer a special shipping method for wholesalers only. In this post, we’ll show you how to do that with a simple WooCommerce snippet.
Why filter shipping methods by user role?
By default, WooCommerce shows the same shipping methods to all users. But with a bit of code, you can customize this behavior to:
- Offer special shipping prices to wholesalers or resellers.
- Restrict premium options to logged-in users.
- Hide fast shipping options from certain customers.
Let’s jump into the code.
Snippet: exclude shipping methods by user role
Add the following snippet to your theme’s functions.php
file (preferably a child theme), or to a custom plugin:
<?php add_filter( 'woocommerce_package_rates', 'filterShippingMethodsByUserRole', 10, 2 ); function filterShippingMethodsByUserRole( $shippingRates, $package ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return $shippingRates; } $currentUser = wp_get_current_user(); $userRoles = (array) $currentUser->roles; // Define the shipping methods you want to hide $excludedMethods = [ 'flat_rate:3', // Change to your actual method ID 'free_shipping:1', // Example: hide "Free Shipping" ]; // Define which roles should have these methods hidden $rolesToRestrict = [ 'customer', 'subscriber' ]; foreach ( $shippingRates as $rateId => $rate ) { if ( in_array( $rateId, $excludedMethods ) && array_intersect( $userRoles, $rolesToRestrict ) ) { unset( $shippingRates[ $rateId ] ); } } return $shippingRates; }
How to find the shipping method ID
To find the correct ID for a shipping method:
- Go to WooCommerce > Settings > Shipping > Shipping Zones.
- Click Edit on a specific zone.
- Hover over a method and check your browser’s status bar. You’ll see something like:
method_id=flat_rate&instance_id=3
Join these two values with a colon to get the final ID:
flat_rate:3
Customize by role or login status
You can easily tweak the previous snippet for different conditions. For example:
- Hide a method only for non-logged-in users:
<?php if ( ! is_user_logged_in() && in_array( $rateId, $excludedMethods ) ) { unset( $shippingRates[ $rateId ] ); }
- Show a method only to administrators:
<?php if ( ! in_array( 'administrator', $userRoles ) && $rateId === 'local_pickup:2' ) { unset( $shippingRates[ $rateId ] ); }
This kind of customization helps you tailor the shopping experience for different user types in WooCommerce. By hiding or showing shipping methods based on user roles, you can streamline your checkout, reward specific customers, or simplify your logistics.