skip to Main Content

I’m trying to update the tax class based on the category being set. I need to use the Reduced Rate for everything in my category "Books". The category ID is 133, and I’m currently using this filter, but it’s not working. What am I missing here?

add_action( 'woocommerce_new_product', 'change_tax_for_books' );

function change_tax_for_books( $id ) {
    if( has_term( 133, 'product_cat', $id ) ) {
        $product = wc_get_product( $id );
        $product->set_tax_class( 'Reduced Rate' );
        $product->save();
    }
}

I’d like to add my WordPress is in Dutch, do I have to use "Gereduceerd Tarief" in this case?

2

Answers


  1. Chosen as BEST ANSWER

    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' );
    

  2. 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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search