php - Auto adjust product tax class based on WooCommerce category
Solution:
Got it! There were a few issues. First off, apparently products are initialized by WordPress before CRUD so woocommerce_new_product
is pretty misleading. It's better to use woocommerce_update_product
.
Next up, when using that you will get in an infinite loop because every time you call save()
, the action runs again, so you need to remove your action and then add it again. See the final code below.
function change_tax_for_books( $id ) {
$product = wc_get_product( $id );
if( has_term( 133, 'product_cat', $id ) ) {
$product->set_tax_class( 'Gereduceerd tarief' );
remove_action( 'woocommerce_update_product', 'change_tax_for_books' );
$product->save();
add_action( 'woocommerce_update_product', 'change_tax_for_books' );
}
}
add_action( 'woocommerce_update_product', 'change_tax_for_books' );
Answer
Solution:
Are you sure it's a filter
and not an action
. Did did a quick scan and only found refs to an action called woocommerce_new_product
:
add_action( 'woocommerce_new_product', 'change_tax_for_books' );
Source