Seb G
Seb G

Reputation: 671

Programmatically remove specific shipping method - WooCommerce

I need to remove my UPS shipping methods on the cart and checkout pages after the cart weight surpasses 150lbs. This is along the lines of what I'm thinking...

function is_it_over_onefifty($available_methods){

        global $woocommerce;
        if ($woocommerce->cart->cart_contents_weight > 150){
            //diable shipping
            unset( $available_methods['ups'] );
        }
        else{

            //do nothing

        }
        return $available_methods;
}
add_filter( 'woocommerce_available_shipping_methods', 'is_it_over_onefifty', 10, 1);

Upvotes: 2

Views: 8509

Answers (2)

Maulik patel
Maulik patel

Reputation: 2442

add_filter( 'woocommerce_package_rates', 'define_default_shipping_method', 10, 2 );
   
function define_default_shipping_method( $rates, $package ) {
      
// Only unset rates if free_shipping is available
if ( isset( $rates['free_shipping:8'] ) ) {
     unset( $rates['flat_rate:4'] );
}     
     
return $rates;
  
}

Upvotes: 1

random_user_name
random_user_name

Reputation: 26160

I had started with a comment, but it became too large.

Below is some solid example code that will get you going where you need to. Note the idea is taken from here: http://www.bolderelements.net/support/knowledgebase/hide-shipping-method-based-on-weight/

add_filter( 'woocommerce_package_rates', 'hide_shipping_weight_based', 10, 2 );

function hide_shipping_weight_based( $rates, $package ) {
    // if you don't know what the rates are, you can uncomment below to see all the rates that are available
    // var_dump( $rates );

    // Set weight variable
    $cart_weight = 0;
 
    // Shipping rate to be excluded
    $shipping_type = 'ups_';
 
    // Calculate cart's total
    foreach( WC()->cart->cart_contents as $key => $value) {
        $cart_weight += $value['data']->weight * $value['quantity'];
    }
    
    // only if the weight is over 150lbs find / remove specific carrier
    if( $cart_weight > 150 ) {
        // loop through all of the available rates
        foreach( $rates AS $id => $data )  {
            // if the rate id starts with "ups_"
            if ( 0 === stripos( $id, $shipping_type ) ) {
                unset( $rates[ $id ] ); // remove it
            }
        }
    }
 
    return $rates;
}

Upvotes: 0

Related Questions