我需要在 WooCommerce 中为帐单地址位于德国境外的公司用户设置不同的税级。一般来说,它总是19%,但在这种情况下,我需要将其设置为0%。我已经使用以下代码片段实现了这一点。但是,它仅适用于结账页面。在感谢页面和发票上,它始终显示 19%,而不是我使用下面的代码片段设置的 0%。我需要的是为特定订单设置 0% 的税级,并确保它在整个采购过程中保持一致。 任何有关解决此问题的指导将不胜感激。
function apply_conditionally_taxes() {
if ( !is_admin() && !empty(WC()->cart->get_cart()) ) {
$billing_country = WC()->customer->get_billing_country();
$post_data = isset( $_POST['post_data'] ) ? wp_unslash( $_POST['post_data'] ) : '';
parse_str( $post_data, $parsed_data );
$billing_company = isset( $parsed_data['billing_company'] ) ? sanitize_text_field( $parsed_data['billing_company'] ) : '';
if ( !empty( $billing_company ) && $billing_country != 'DE' ) {
$cart_item['data']->set_tax_class( 'Online World' );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 99, 1 );
我正在提供更多详细信息以澄清情况。没有使用自定义表格;相反,我仅依赖标准的 WooCommerce 结账表单,特别关注帐单地址字段。尽管前面提到的代码片段在结帐页面上可以正常运行,但当用户继续完成购买时,它始终会恢复为默认税率。
为了确保在整个采购过程中德国境外的公司用户的税级始终设置为 0%,您需要调整方法。您提供的代码的问题在于,它仅在 woocommerce_before_calculate_totals 操作期间修改税级,这可能无法涵盖所有场景。
要实现更一致的税级设置,您可以使用 woocommerce_before_calculate_totals 挂钩以及覆盖购买流程不同阶段的其他挂钩,例如 woocommerce_checkout_create_order 和 woocommerce_checkout_update_order_meta 挂钩。
这是更新的代码片段:
function apply_conditionally_taxes( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$billing_country = WC()->customer->get_billing_country();
$billing_company = WC()->customer->get_billing_company();
if ( ! empty( $billing_company ) && $billing_country !== 'DE' ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 10, 1 );
function set_order_tax_class( $order_id ) {
$order = wc_get_order( $order_id );
$billing_country = $order->get_billing_country();
$billing_company = $order->get_billing_company();
if ( ! empty( $billing_company ) && $billing_country !== 'DE' ) {
foreach ( $order->get_items() as $item_id => $item ) {
$item->set_tax_class( 'zero-rate' );
}
}
}
add_action( 'woocommerce_checkout_create_order', 'set_order_tax_class', 10, 1 );
add_action( 'woocommerce_checkout_update_order_meta', 'set_order_tax_class', 10, 1 );
确保您在 WooCommerce 设置中设置了名为“Online World”的税级,税率为 0%。
此代码将在购物车计算期间将税级设置为“零税率”,并将在订单创建过程中更新订单中每个商品的税级。根据您的实际设置相应调整税级名称(“零税率”)。