2

我试图找到一种方法,我只能显示产品具有的税率(16% 或 7%)。基本上这个想法是应该有一个静态税。

价格包括 16% 税

或者

价格包括 7% 税

因此,百分比应该是动态的,取决于产品的比率。

任何想法如何解决这个问题。我找到的所有解决方案都显示了完整的税额,但我只需要税率。

4

1 回答 1

3

税费取决于您的设置,即一个或多个税级以及客户所在地的每个税级。在下面,您将找到获取和显示产品税率的正确方法(在 WooCommerce 上设置):

// Get the WC_Product Object
global $product;

if( ! is_a( $product, 'WC_Product' ) ) {
    $product = wc_get_product( get_the_id() );
}

// Get an instance of the WC_Tax object
$tax_obj = new WC_Tax();

// Get the tax data from customer location and product tax class
$tax_rates_data = $tax_obj->find_rates( array(
    'country'   => WC()->customer->get_shipping_country() ? WC()->customer->get_shipping_country() : WC()->customer->get_billing_country(),
    'state'     => WC()->customer->get_shipping_state() ? WC()->customer->get_shipping_state() : WC()->customer->get_billing_state(),
    'city'      => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
    'postcode'  => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
    'tax_class' => $product->get_tax_class()
) );

// Finally we get the tax rate (percentage number) and display it:
if( ! empty($tax_rates_data) ) {
    $tax_rate = reset($tax_rates_data)['rate'];

    // The display
    printf( '<span class="tax-rate">' . __("The price includes %s Taxes", "woocommerce") . '</span>',  $tax_rate . '%' );
}

测试和工作。您可以将该代码嵌入到可以重用的函数中。


使用示例:

在价格下方显示单个产品的税率(使用挂钩函数)

add_action( 'woocommerce_single_product_summary', 'display_tax_rate_on_single_product', 15 );
function display_tax_rate_on_single_product() {
    global $product; // The current WC_Product Object instance

    // Get an instance of the WC_Tax object
    $tax_obj = new WC_Tax();
    
    // Get the tax data from customer location and product tax class
    $tax_rates_data = $tax_obj->find_rates( array(
        'country'   => WC()->customer->get_shipping_country() ? WC()->customer->get_shipping_country() : WC()->customer->get_billing_country(),
        'state'     => WC()->customer->get_shipping_state() ? WC()->customer->get_shipping_state() : WC()->customer->get_billing_state(),
        'city'      => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
        'postcode'  => WC()->customer->get_shipping_city() ? WC()->customer->get_shipping_city() : WC()->customer->get_billing_city(),
        'tax_class' => $product->get_tax_class()
    ) );
    
    // Finally we get the tax rate (percentage number) and display it:
    if( ! empty($tax_rates_data) ) {
        $tax_rate = reset($tax_rates_data)['rate'];
    
        // The display
        printf( '<span class="tax-rate">' . __("The price includes %s Taxes", "woocommerce") . '</span>',  $tax_rate . '%' );
    }
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。

相关:分别获取 Woocommerce 中每个购物车和订单商品的税率

于 2020-10-05T22:10:42.123 回答