Skip to content

Instantly share code, notes, and snippets.

@isotrope
Last active February 23, 2021 23:19
Show Gist options
  • Save isotrope/7e4f1eb439050fe4acf29f93dfa5ea50 to your computer and use it in GitHub Desktop.
Save isotrope/7e4f1eb439050fe4acf29f93dfa5ea50 to your computer and use it in GitHub Desktop.
Calculer si on a assez de produits d'une catégorie X. Si oui, ajuster leur status de taxe
<?php
add_action( 'woocommerce_before_calculate_totals', 'naj_apply_conditionally_taxes', 20, 1 );
function naj_apply_conditionally_taxes( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$num_taxables = 0;
$min_taxables_before_applying_zero_rate = 6;
foreach ( $cart->get_cart() as $cart_item ) {
// Est-ce un produit taxable?
$_product = wc_get_product( $cart_item['data']->get_id() );
if ( $_product && $_product->is_taxable() ) {
// ...oui? alors, additions les quantités
$num_taxables = $num_taxables + intval( $cart_item['quantity'] );
if ( $num_taxables >= $min_taxables_before_applying_zero_rate ) {
// on en a plus qu'assez. Ça ne donne rien de continuer cette boucle
break;
}
}
}
// en avons-nous 6 ou plus (de taxables)?
if ( $num_taxables >= $min_taxables_before_applying_zero_rate ) {
// ... alors appliquons la classe désirée à tout le monde (qui est taxable)
$_product = wc_get_product( $cart_item['data']->get_id() );
if ( $_product && $_product->is_taxable() ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment