php - WooCommerce Free Shipping if over 5 pounds -
i'm trying write function offer free shipping (remove other options) if order on 5 pounds (80 ounces), doesn't work although code seems correct.
this have:
// hide shipping options free when on 80 ounches (5 pounds) add_filter( 'woocommerce_available_shipping_methods', 'ship_free_if_over_five_pounds' , 10, 1 ); /** * hide shipping option free if on 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) : // free shipping array new array $freeshipping = array(); $freeshipping = $available_methods['free_shipping']; // empty $available_methods array unset( $available_methods ); // add free shipping $avaialble_methods $available_methods = array(); $available_methods[] = $freeshipping; endif; return $available_methods; } any thoughts?
the code based on example #19 on site:
my 25 best woocommerce snippets wordpress part 2
i know old question, have recent alternative…
first, in code "if order on 5 pounds (80 ounces)" if statement should if($whats_the_weight > 80) instead of !=… think code little outdated if use woocommerce 2.6+.
after instead using global $woocommerce; $woocommerce->cart->cart_contents_weight; use: wc()->cart->cart_contents_weight;
i have more recent code snippet based on official thread woocommerce 2.6+. should try it:
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 ); function my_hide_shipping_when_free_is_available( $rates ) { $cart_weight = wc()->cart->cart_contents_weight; // cart total weight $free = array(); foreach ( $rates $rate_id => $rate ) { if ( 'free_shipping' === $rate->method_id && $cart_weight > 80 ) { // <= weight condition $free[ $rate_id ] = $rate; break; } } return ! empty( $free ) ? $free : $rates; } for woocommerce 2.5, should try this:
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 ); function hide_shipping_when_free_is_available( $rates, $package ) { $cart_weight = wc()->cart->cart_contents_weight; // cart total weight // modify rates if free_shipping present if ( isset( $rates['free_shipping'] ) && $cart_weight > 80 ) { // here weight condition // unset single rate/method, following. example unsets flat_rate shipping unset( $rates['flat_rate'] ); // unset methods except free_shipping, following $free_shipping = $rates['free_shipping']; $rates = array(); $rates['free_shipping'] = $free_shipping; } return $rates; }
Comments
Post a Comment