Puddinq.com sharing knowledge

Use costs shippingclass for all products in WooCoomerce cart

Use costs shippingclass for all products in WooCoomerce cart

In a situation where you want the shipping costs determinined by a shipping class to apply for all products in the cart (and not use the highest price).

/**
 * When one of the products has a 'free-shipping' class wich gives a discount on shipping
 * => and you want it to apply to all the products in the cart
 * (so it will not present the highest price, but the discount price)
 */

add_filter( 'woocommerce_cart_shipping_packages', 'puddinq_woocommerce_cart_shipping_packages' );

function puddinq_woocommerce_cart_shipping_packages( $packages ) {

    $free = false;

    // check if a product with the shipping class 'free-shipping' is in the cart
	// if so get the id of the shipping methode
    foreach (WC()->cart->get_cart() as $item) {
        if ($item['data']->get_shipping_class() == 'free-shipping') {
            $free = true;
            $id = $item['data']->get_shipping_class_id();
        }
    }

	// if the free-shipping was found apply it to all items
    if ($free) {
        foreach (WC()->cart->get_cart() as $item) {
            $item['data']->set_shipping_class_id($id);
        }
    }

    return $packages;
}