I run an online store with WooCommerce and sell normal products and books. I want to reach the following:
- If somebody has a cart value of < 50 he should pay for shipping
- If somebody has a cart value of > 50 shipping should be free
- If somebody adds a book to the cart shipping is always free
I try this with the following code:
function custom_free_per_class( $return, $package ) {
// Setup an array of shipping classes that allow Flat Rate Shipping
$shippingclass_array = array( 'bookshipping');
// loop through the cart checking the shipping classes
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$shipping_class = get_the_terms( $values['product_id'], 'product_shipping_class' );
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass_array ) ) {
return true;
break;
}//if
}//foreach
}//function
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'custom_free_per_class', 10, 2 );
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
/**
* Hide shipping rates when free shipping is available
*
* @param array $rates Array of rates found for the package
* @param array $package The package array/object being shipped
* @return array of modified rates
*/
function hide_shipping_when_free_is_available( $rates, $package ) {
// Only modify rates if free_shipping is present
if ( isset( $rates['free_shipping'] ) ) {
// To unset all methods except for free_shipping, do the following
$free_shipping = $rates['free_shipping'];
$rates = array();
$rates['free_shipping'] = $free_shipping;
}
return $rates;
}
I set it up in the WooCommerce backend that free shipping should be available after a cart value of 50 has been reached. But however this does not work. The above code works - so free shipping is guaranteed when somebody adds a book, but this seems to hinder the other intention (cart > 50) from working. If I remove the code
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'custom_free_per_class', 10, 2 );
the functionality with adding free shipping when 50 is reached works, but surely books are not free anymore.
Des anybody has an idea what is going wrong here? I would really appreciate it if anyone can help me.
Thanks!