1
votes

I am excluding virtual products from free shipping, with the working code below. However the 'flexible_shipping_12_1 and _12_2 rates are being problematic because they get removed when the free shipping threshold is crossed.

For example a user buys a virtual product worth $20 and other products worth $26, this makes the order total $46 which would qualify them for free shipping. Because they qualify for free shipping, the other rates are removed.

The code below checks to see that the non-virtual total is actually only $26 so they shouldn't get free shipping. They do qualify for the $26-$44.99 rate. This part is working.

If free shipping is removed they should get the next tier of shipping which is: ID= flexible_shipping_12_2. This method has removed itself because it thinks the order total is $46.

I need to 're-insert', not create, that method and # _12_1 into the available shipping methods at the spots indicated in the code below.

I can't figure out how to re-insert a shipping method:

//Exclude virtual products from free shipping

add_filter('woocommerce_package_rates', 'custom_shipping_option', 20, 2 );

function custom_shipping_option($rates, $package){

  $non_virtual_total = 0;

  // Get the cart content total excluding virtual products

  foreach( WC()->cart->get_cart() as $cart_item )

    if( ! $cart_item['data']->is_virtual( ) ){
        $non_virtual_total += $cart_item['line_total'];
    }

  // Disabling methods based on non_virtual_total

 if( $non_virtual_total <  45 && $non_virtual_total >= 25 ){

  foreach ( $rates as $rate_key => $rate )

  if( 'free_shipping' == $rate->method_id )
  unset( $rates[ $rate_key ] );

  if( 'flexible_shipping_12_1' == $rate->method_id )
  unset( $rates[ $rate_key ] );

  //insert flexible_shipping_12_2 method here

        }


    if( $non_virtual_total <  25 ){

    foreach ( $rates as $rate_key => $rate )
    if( 'free_shipping' == $rate->method_id )
      unset( $rates[ $rate_key ] );

    if( 'flexible_shipping_12_2' == $rate->method_id )
      unset( $rates[ $rate_key ] );

    //insert flexible_shipping_12_1 method here 


        }       

return $rates;

}

1

1 Answers

1
votes

I believe you just want to re-add flexible_shipping_12_1 or flexible_shipping_12_2 shipping method to the $rates array, correct?

This should be all you need:

//insert flexible_shipping_12_1 method here
array_push($rates, "flexible_shipping_12_1");

//insert flexible_shipping_12_2 method here
array_push($rates, "flexible_shipping_12_2");

The array_push method just adds the new value to the array.