Woocommerce Charges shipping/disables free if shipping class products are alone in cart

  php, shipping, woocommerce, wordpress

we have a large variety of products in our store, some of which are not our own and supplied. I am trying to set up a functionality where free shipping is disabled if the products in the cart are of a certain shipping class ‘Extra’ AND alone. ei there are only products of that particular shipping class in cart.

If there are any other products with it that are not in the shipping class ‘Extra’, free shipping would still appliy. So if 5 products are in cart all with shipping class ‘Extra’ and no other products, there is a $5 carge. If there is any other product that is not in that shipping class, free shipping applies again. Ive scoured the internet for solutions and this is what I got so far however it doesnt seem to be working. I have products already in the shipping class Extra, however whenever I add them to cart there is still free shipping

function hide_shipping_methods( $available_shipping_methods, $package ) {
    $shipping_classes = array( 'Extra', 'some-shipping-class-2' );
    $excluded_methods = array( 'free_shipping' );
    $found = $others = false;
    $shipping_class_exists = false;
    
    foreach( $package['contents'] as $key => $value )
        if ( in_array( $value['data']->get_shipping_class(), $shipping_classes ) ) {
            $shipping_class_exists = true;
            break;
        }else {
            $others = true; // NOT the shipping class
            break;
        }
    if ( $shipping_class_exists && !others) {
        $methods_to_exclude = array();
        foreach( $available_shipping_methods as $method => $method_obj )
            if ( in_array( $method_obj->method_id, $excluded_methods ) )
                $methods_to_exclude[] = $method;
        if ( $methods_to_exclude )
            foreach ( $methods_to_exclude as $method )
                unset( $available_shipping_methods[$method] );
    }
    return $available_shipping_methods;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods', 10, 2 );

Source: Ask PHP

LEAVE A COMMENT