Search code examples
phpwordpresswoocommerceproduct

Get the label of a product tax rate in WooCommerce


I need to find out the label of the tax rate in WooCommerce.

With the following code I can find out the tax rate:

$taxclass = $product_variation->get_tax_class();
 $tax_rates = WC_Tax::get_rates( $taxclass );
if (!empty($tax_rates)) {
    $tax_rate = reset($tax_rates);
    $tax_rate_info = (int)$tax_rate['rate'];
}
else {
}

Unfortunately I can not get the exact label of that tax rate. I have tried the following:

 $tax_labels = WC_Tax::get_rate_label( $taxclass );

I need to somehow find out the id of the tax rate and pass the id to the get_rate_label() so it functions. Can somebody please help how to find the tax rate id.


Solution

  • You can get the label name of a specific tax rate using the array key label as follow:

    $variation_tax_class  = $product_variation->get_tax_class();
    $variation_tax_rates  = WC_Tax::get_rates( $variation_tax_class );
    
    foreach( $variation_tax_rates as $rate_id => $rate ) {
        if ( ! empty($rate) ) {
            $rate_percent  = (int) $rate['rate'];
            $rate_label    = $rate['label']; // <== HERE is the label name of the tax rate
            $rate_shipping = $rate['shipping'];
            $rate_compound = $rate['compound'];
        }
    }