Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewlimaza/d523c6a773d9030556d2730fd7453e36 to your computer and use it in GitHub Desktop.
Save andrewlimaza/d523c6a773d9030556d2730fd7453e36 to your computer and use it in GitHub Desktop.
Hide shipping method for non-wholesale customers WooCommerce.
<?php
/**
* Removes shipping methods for non-wholesale customers.
* Please be sure to clear your WooCommerce store's cache.
* Adjust 'flat_rate:2' to match that of your wholesale shipping method.
*/
function my_wcs_remove_shipping_non_wholesale( $rates, $package ){
global $current_user;
$is_wholesale = get_user_meta( $current_user->ID, 'wcs_wholesale_customer', true );
if ( ! $is_wholesale ) {
foreach( $rates as $method ) {
if ( $method->id == 'flat_rate:2' ) {
unset( $rates[$method->id] );
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'my_wcs_remove_shipping_non_wholesale', 10, 2 );
@martini09617
Copy link

Thanks sir, but how to make it work for more then 1 shipment ID? I want to add flat_rate:13

@martini09617
Copy link

martini09617 commented Aug 3, 2022

The following code is the newest version, but it doesn't work for me. What is wrong?

``add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_wholesale_customer', 10, 2 );
function shipping_methods_based_on_wholesale_customer( $rates, $package ){
$is_wholesale = get_user_meta( get_current_user_id(), 'wcs_wholesale_customer', true );

// Set the shipping methods rate ids in the arrays:
if( $is_wholesale ) {
    $shipping_rates_ids = array('flat_rate:1', 'flat_rate:4'); // To be removed for NON Wholesale users
} else {
    $shipping_rates_ids = array('flat_rate:2'); // To be removed for Wholesale users
}

// Loop through shipping rates fro the current shipping package
foreach( $rates as $rate_key => $rate ) {
    if ( in_array( $rate_key, $shipping_rates_ids) ) {
        unset( $rates[$rate_key] ); 
    }
}

return $rates;

}``

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment