根据WooCommerce类别自动调整产品税类

问题描述

我正在尝试根据设置的类别更新税种。我需要对“书籍”类别中的所有内容使用“降低的价格”。类别ID为133,我目前正在使用此过滤器,但无法正常工作。我在这里想念什么?

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();
    }
}

我想添加我的wordpress为荷兰语,在这种情况下是否必须使用“ Gereduceerd Tarief”?

解决方法

您确定它是filter而不是action。做了快速扫描,只发现引用了名为woocommerce_new_product的操作:

add_action( 'woocommerce_new_product','change_tax_for_books' );
,

知道了!有几个问题。首先,显然产品是在CRUD之前由WordPress初始化的,因此woocommerce_new_product颇具误导性。最好使用woocommerce_update_product

接下来,当使用它时,您将陷入无限循环,因为每次调用save()时,操作都会再次运行,因此您需要删除操作然后再次添加。请参阅下面的最终代码。

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