Last active
January 26, 2021 14:41
-
-
Save FrancoStino/4c08459fbd1d9bb4e495d383af7869c4 to your computer and use it in GitHub Desktop.
Add Free shipping conditionally with specific category on cart and minimum order for this category
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
/** | |
* 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 = 'Cannabis Light'; ## ID Categoria prodotto o slug o intero titolo della categoria | |
$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; | |
// Get non discounted subtotal including taxes from subcategories | |
$subtotal += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax']; | |
}else{ | |
$others = true; | |
} | |
} | |
if ( $found ) { // Se c'è la categoria | |
foreach($rates as $rate_id => $rate) { | |
if ('wbs' === $rate->method_id && $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 && $subtotal < 50 ){ | |
// Display an error notice (and avoid checkout) | |
wc_add_notice( sprintf( | |
__( "Devi spendere almeno %s in %s per usufruire delle spedizione gratuita!", "woocommerce" ), | |
wc_price('50'), | |
'"<strong>' . ucfirst($term) . '</strong>"' | |
), 'error' ); | |
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