Ad

Hide Free Shipping When Subtotal Is Greater Than 0 In WooCommerce

I'm using Free Product Sample for the WooCommerce plugin and trying to set conditional free shipping only for a Sample product, sample product cost is 0 and therefore I'm trying to hide free shipping unless the order subtotal amount is 0.

To put it in a nutshell:

I want to offer free shipping only for sample products and, the free shipping method should only visible for a product having subtotal = 0

Screenshot for further clarification:

free_shipping_image


My attempted code:

function ts_hide_shipping_for_order_total( $rates ) {
  $rate = array();
  $order_total = WC()->cart->get_subtotal();
  
  if( $order_total > 0 ) {
    foreach ( $rates as $rate_id => $rate ) {
      if ( 'free_shipping:20' === $rate->get_method_id() ) {
        $rate[ $rate_id ] = $rate;
      }
    }
  }
  return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_for_order_total', 100 );

OR

add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
function hide_shipping_except_local_when_free_is_available($rates) {
    $free = $local = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping:20' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
        }
    }
    return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
}

But both codes do not give me the desired result. Can anyone point me in the right direction?

Ad

Answer

To hide/unset the "free shipping", as long as the subtotal is greater than 0, you can use the following.

So you get:

function filter_woocommerce_package_rates( $rates, $package ) {
    // Get subtotal
    $subtotal = $package['cart_subtotal'];
    
    // Hide free shipping if subtotal > 0
    if ( $subtotal > 0 ) {
        // Loop trough
        foreach ( $rates as $rate_id => $rate ) {
            if ( $rate->method_id === 'free_shipping' ) {
                unset( $rates[$rate_id] );
            }
        }   
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

Additional question: Hide the other methods when subtotal <= 0

function filter_woocommerce_package_rates( $rates, $package ) { 
    // Get subtotal
    $subtotal = $package['cart_subtotal'];
    
    // Loop trough
    foreach ( $rates as $rate_id => $rate ) {
        if ( $rate->method_id === 'free_shipping' ) {
            // Hide free shipping if subtotal > 0
            if ( $subtotal > 0 ) {
                unset( $rates[$rate_id] );
            }
        } else {
            // Hide other methods when subtotal <= 0
            if ( $subtotal <= 0 ) {
                unset( $rates[$rate_id] );
            }               
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
Ad
source: stackoverflow.com
Ad