I'd like to add a woocommerce function that creates a shortcode who displays the tax amount from a single product in the product page.
The optimal solution would be to do the math(productprice * 0,25) directly in the php function and echo the result, cause we sell our products without tax. The reason for this script is to show our costumers approx how much tax they will pay during import a product from a none EU country.
I.e. Product price: $100 Tax rate 25 % Tax amount $25
I'd like to show the tax amount with a shortcode, something like this:
Total tax amount for this product: $25
Thanks!
This can be done easily with the following code:
if( ! function_exists('get_formatted_product_tax_amount') ) {
function get_formatted_product_tax_amount( $atts ) {
// Attributes
$atts = shortcode_atts( array(
'id' => '0',
), $atts, 'tax_amount' );
global $product, $post;
if( ! is_object( $product ) || $atts['id'] != 0 ){
if( is_object( $post ) && $atts['id'] == 0 )
$product_id = $post->ID;
else
$product_id = $atts['id'];
$product = wc_get_product( $product_id );
}
if( is_object( $product ) ){
$price_excl_tax = wc_get_price_excluding_tax($product);
$price_incl_tax = wc_get_price_including_tax($product);
$tax_amount = $price_incl_tax - $price_excl_tax;
return wc_price($tax_amount);
}
}
add_shortcode( 'tax_amount', 'get_formatted_product_tax_amount' );
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works
USAGE (examples):
1) In single product pages, in short description text editor:
Total tax amount for this product: [tax_amount]
2) For single product pages, in php code:
$text = __('Total tax amount for this product', 'woocommerce');
echo '<p>' . $text . ': ' . do_shortcode("[tax_amount]") . '</p>';
3) On other pages, in text editor (set the product Id as a parameter):
Total tax amount for this product: [tax_amount id="37"]
4) Anywhere, in php code (set the product Id as a parameter):
$text = __('Total tax amount for this product', 'woocommerce');
echo '<p>' . $text . ': ' . do_shortcode("[tax_amount id='37']") . '</p>';