MediaCreandum
MediaCreandum

Reputation: 123

Require minimum weight for delivery method in WooCommerce

In the Woocommerce store there are 3 shipping options

Inspired by Free shipping depending on weight and on minimal cart amount I would like to require a minimum total cart weight when choosing an shipping option.


On the internet I found WooCommerce: How to Setup Tiered Shipping Rates by Order Amount, which I customized to work properly on the store because we have 2 shipping zones (so multiple flat rates, local pickup, etc).

Unfortunately it does not work for my needs, while I think the code is correct? Any help will be much appreciated.

add_filter( 'woocommerce_package_rates', 'bbloomer_woocommerce_tiered_shipping', 9999, 2 );

function bbloomer_woocommerce_tiered_shipping( $rates, $package ) {
 
 if ( WC()->cart->get_cart_contents_weight() < 25 ) {
   
     if ( isset( $rates['local_pickup:5'], $rates['local_pickup:9'] ) ) unset( $rates['flat_rate:3'], $rates['flat_rate:6'], $rates['free_shipping:1'], $rates['free_shipping:8'] );
   
 } elseif ( WC()->cart->get_cart_contents_weight() < 50 ) {
   
     if ( isset( $rates['flat_rate:3'], $rates['flat_rate:6'], $rates['local_pickup:5'], $rates['local_pickup:9'] ) ) unset( $rates['free_shipping:1'], $rates['free_shipping:8'] );
   
 } else {
   
     if ( isset( $rates['free_shipping:1'], $rates['free_shipping:8'],  $rates['local_pickup:5'], $rates['local_pickup:9'] ) ) unset( $rates['flat_rate:3'], $rates['flat_rate:6'] );
   
 }

 return $rates;

}

Upvotes: 0

Views: 365

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29650

Note: you cannot add multiple conditions to an if condition in the way you apply it.


Add the shipping options you want to keep under a certain condition to the $available_shipping array

  • When customers order for 24kg or less = local pickup
  • If the total cart weight is between 25kg and 49kg = local pickup and flat rate
  • If the total cart weight is 50 kg and above = local pickup and free shipping
function filter_woocommerce_package_rates( $rates, $package ) { 
    // Get cart contents weight
    $weight = WC()->cart->get_cart_contents_weight();
 
    // Conditions
    if ( $weight <= 24 ) {
        // Set available shipping options
        $available_shipping = array( 'local_pickup' );
    } elseif ( $weight > 24 || $weight < 50 ) {
        $available_shipping = array( 'local_pickup', 'flat_rate' );
    } else {
        $available_shipping = array( 'local_pickup', 'free_shipping' );
    }
    
    foreach ( $rates as $rate_key => $rate ) {
        // Targeting, NOT in array
        if ( ! in_array( $rate->method_id, $available_shipping ) ) {
            unset( $rates[$rate_key] );
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

Upvotes: 1

Related Questions