6

I made a customization of WooCommerce in my WordPress installation.

I have something like follow:

/**
 * Disable free shipping for select products
 *
 * @param bool $is_available
 */
function my_free_shipping( $is_available ) {
    global $woocommerce;

    // set the product ids that are ineligible
    $ineligible = array( '14009', '14031' );

    // get cart contents
    $cart_items = $woocommerce->cart->get_cart();

    // loop through the items looking for one in the ineligible array
    foreach ( $cart_items as $key => $item ) {
        if( in_array( $item['product_id'], $ineligible ) ) {
            return false;
        }
    }

    // nothing found return the default value
    return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'my_free_shipping', 20 );

Updating WordPress and WooCommerce, I see that filter "woocommerce_shipping_free_shipping_is_available" is never trigged.

What's wrong?

I found that woocommerce_available_shipping_methods filter is deprecated and now we must use the woocommerce_package_rates one.

Is woocommerce_shipping_free_shipping_is_available deprecated too or I've got problem in my installation?

UPDATE

Finally I'm using two hooks: woocommerce_shipping_free_shipping_is_available and woocommerce_package_rates.

It seems woocommerce_shipping_free_shipping_is_available hook is not deprecated.

This is my code:

add_filter('woocommerce_shipping_free_shipping_is_available', array( $this, 'enable_free_shipping'), 40, 1);            
if ( version_compare( WOOCOMMERCE_VERSION, '2.1', '>' ) ){
  add_filter('woocommerce_package_rates', array( $this, 'free_shipping_filter'), 10, 1);
}else{
  add_filter('woocommerce_available_shipping_methods', array( $this, 'free_shipping_filter'), 10, 1);
}

function enable_free_shipping($is_available){
    global $woocommerce;
    if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
        /* some check here to enable or not free shipping */
        return $is_available;
    }else{
        return $is_available;
    }
}

function free_shipping_filter( $available_methods )
{
    foreach ($available_methods as $key => $method) {
        if ($method->method_id == 'free_shipping'){
            $available_methods = array();
            $available_methods['free_shipping:1'] = $method;
            break;                      
        }
    }
    return $available_methods;
}

enable_free_shipping
Enable or not the free shipping method

free_shipping_filter
Show only free shipping method (if it is enabled)

The reason why the hook doesn't work fine is because the free shipping method must be enabled only for a valid coupon. In this way ordinary users doesn't see the "free shipping method" but I can enabled it via the hook woocommerce_shipping_free_shipping_is_available.

Gerhard
  • 6,850
  • 8
  • 51
  • 81
Zauker
  • 2,344
  • 3
  • 27
  • 36

0 Answers0