businessdad

Tax Display by Country - Fixed shipping costs

Jun 15th, 2020
1,017
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.31 KB | None | 0 0
  1. /**
  2.  * Tax Display by Country - Keep shipping prices fixed, no matter the applicable taxes.
  3.  *
  4.  * HOW TO USE THIS CODE
  5.  * Ad the code to the bottom of your theme's functions.php file, and it should run automatically.
  6.  * If you're not familiar with the implementation of custom code on a WordPress site, please refer
  7.  * to the following article: https://www.skyverge.com/blog/add-custom-code-to-wordpress/
  8.  *
  9.  * DISCLAIMER
  10.  * Aelia and any member of its staff are not responsible for any data loss or damage incurred
  11.  * when using the code, which you can use at your own risk.
  12.  *
  13.  * GPL DISCLAIMER
  14.  * Because this code program is free of charge, there is no warranty for it, to the extent permitted by applicable law.
  15.  * Except when otherwise stated in writing the copyright holders and/or other parties provide the program "as is"
  16.  * without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of
  17.  * merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the program
  18.  * is with you. should the program prove defective, you assume the cost of all necessary servicing, repair or correction.
  19.  *
  20.  * Need a consultation, or assistance to customise this code? Find us on Codeable: https://aelia.co/hire_us
  21.  */
  22.  
  23. /**
  24.  * Intercepts a shipping rate added by WooCommerce, to perform the following operations:
  25.  * - Recalculates the shipping cost before tax.
  26.  * - Recalculate the tax.
  27.  * The targe is to ensure that the final cost, inclusive of tax, remains the same no matter
  28.  * what VAT rate applies to it.
  29.  *
  30.  * @param array $rate
  31.  * @param array $args
  32.  * @param WC_Shipping_Method $shipping_method
  33.  * @return array
  34.  */
  35. add_filter('woocommerce_shipping_method_add_rate', function($rate, $args, $shipping_method) {
  36.   $original_taxes = array_sum($rate->get_taxes());
  37.   // No need to perform a recalculation if either taxes or costs are zero (or negative, in
  38.   // which case they are not valid)
  39.   if(($original_taxes <= 0) || ($rate->get_cost() <= 0)) {
  40.     return $rate;
  41.   }
  42.   $recalc_ratio = $rate->get_cost() / ($rate->get_cost() + $original_taxes);
  43.   $rate->set_cost(round($rate->get_cost() * $recalc_ratio, 2));
  44.  
  45.   $taxes = ($args['calc_tax'] === 'per_item') ? $shipping_method->get_taxes_per_item($rate->get_cost()) : WC_Tax::calc_shipping_tax($rate->get_cost(), WC_Tax::get_shipping_tax_rates());
  46.   $rate->set_taxes($taxes);
  47.   return $rate;
  48. }, 999, 3);
Add Comment
Please, Sign In to add comment