I'm trying to write a function that will offer free shipping only (remove all other options) if the order is over 5 pounds (80 ounces), but it doesn't work although the code seems correct.
This is what I have:
// Hide ALL shipping options but FREe when over 80 ounches (5 pounds)
add_filter( 'woocommerce_available_shipping_methods', 'ship_free_if_over_five_pounds' , 10, 1 );
/**
* Hide ALL Shipping option but free if over 5 pounds
*
* @param array $available_methods
*/
function ship_free_if_over_five_pounds( $available_methods ) {
global $woocommerce;
$whats_the_weight = $woocommerce->cart->cart_contents_weight;
if($whats_the_weight != 80) :
// Get Free Shipping array into a new array
$freeshipping = array();
$freeshipping = $available_methods['free_shipping'];
// Empty the $available_methods array
unset( $available_methods );
// Add Free Shipping back into $avaialble_methods
$available_methods = array();
$available_methods[] = $freeshipping;
endif;
return $available_methods;
}
Any thoughts?
The code is based on example #19 on this site:
My 25 Best WooCommerce Snippets For WordPress Part 2
I've made an plugin where you can set the maximum weight for free shipping!
Take an look at: http://wordpress.org/plugins/woocommerce-advanced-free-shipping/
I know that this is an old question, but I have this recent alternative…
First, in your code "if the order is over 5 pounds (80 ounces)" your
if
statement should beif($whats_the_weight > 80)
instead of!=
… But i think that your code is a little outdated if you use WooCommerce 2.6+.After instead using
global $woocommerce;
with$woocommerce->cart->cart_contents_weight;
you could use:WC()->cart->cart_contents_weight;
I have this much more recent code snippet based on this official thread for WooCommerce 2.6+. You should try it:
For WooCommerce 2.5, You should try this: