Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/110de50f6d1904f94fa61a3e63d1708f to your computer and use it in GitHub Desktop.
Save FrancoStino/110de50f6d1904f94fa61a3e63d1708f to your computer and use it in GitHub Desktop.
Add Free shipping conditionally with certain category on cart and minimum order
<?php
/**
* Add Free shipping conditionally with certain category on cart and minimum order
*/
add_filter( 'woocommerce_package_rates', 'hide_shipping_flat_rate_conditionaly', 90, 2 );
function hide_shipping_flat_rate_conditionaly( $rates, $package ){
// HERE Define your product category (ID, slug or name or an array of values)
$term = '52'; ## ID Categoria prodotto
$others = $found = false;
// Loop dove cerca se c'è la categoria nel carrello
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
if ( has_term( $term, 'product_cat', $cart_item['product_id'] ) )
$found = true;
else
$others = true;
}
if ( $found ) { // Se c'è la categoria
foreach($rates as $rate_id => $rate) {
if ('wbs' === $rate->method_id && WC()->cart->subtotal >= 50 ){ // Se c'è il flat rate maggiore di 50 euro nel subtotale
unset($rates[ $rate_id ]); // Disattiva flat rate
}elseif('free_shipping' === $rate->method_id && WC()->cart->subtotal < 50 ){ // Altrimenti se c'è la spedizione gratuita al di sotto dei 50 euro nel subtotale
unset($rates[ $rate_id ]); // Disattiva free shipping
}
}
}
elseif ( $other || ! $found ) { // Altrimenti se ci sono altre categorie
foreach($rates as $rate_id => $rate) {
if ('free_shipping' === $rate->method_id /*&& WC()->cart->subtotal > 50 || WC()->cart->subtotal < 50 */ ){ // Se c'è il free shipping a prescindere
unset($rates[ $rate_id ]);
}/*elseif('free_shipping' === $rate->method_id && WC()->cart->subtotal < 50 ){
unset($rates[ $rate_id ]);
}*/
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment