PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] Disable VAT for specific countries in WooCommerce

 March 03, 2022     php, woocommerce, wordpress     No comments   

Issue

Original code makes all prices set to the same, no matter what the VAT % is. So if a item cost 100$ with 25% VAT, it will cost 100$ with 80% VAT or even 0% VAT.

That works fine, however, some countries I would like to remove the VAT for.

Original code from this answer thread:

add_filter( 'woocommerce_adjust_non_base_location_prices', '__return_false' );

My code that is not working:

add_filter( 'woocommerce_adjust_non_base_location_prices', 'custom_eu_vat_number_country_codes' );
function custom_eu_vat_number_country_codes( $vat_countries ) {

// Which countries should it be applide to?
    $countries = array( 'AX', 'AT', 'BE', 'BA', 'HR', 'CZ', 'DK', 'FI', 'GR', 'HU', 'IS', 'IE', 'IT', 'LU', 'NL', 'PO', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'CH', 'GB');

    // Avoiding errors on admin and on other pages
    if( is_admin() || WC()->cart->is_empty() )
        return $countries;

// Remove field $countries
if (($key = array_search($countries, $vat_countries)) !== false) {
    return false;
}
return $vat_countries;
}

What am I doing wrong?


Solution

The main function argument is not related to countries, it's a boolean value (true by default), see that on wc_get_price_excluding_tax() function code..

You need to get the customer billing country from WC_Customer Object (or the shipping country).

So your code should be:

add_filter( 'woocommerce_adjust_non_base_location_prices', 'custom_eu_vat_number_country_codes' );
function custom_eu_vat_number_country_codes( $boolean ) {
    // Avoiding errors on admin and on other pages
    if( is_admin() || WC()->cart->is_empty() )
        return $boolean;

    // Defined array of countries where the boolean value should be "false"
    $countries = array( 'AX', 'AT', 'BE', 'BA', 'HR', 'CZ', 'DK', 'FI', 'GR', 'HU', 'IS', 'IE', 'IT', 'LU', 'NL', 'PO', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'CH', 'GB');

    // Remove field $countries
    if ( in_array( WC()->customer->get_billing_country(), $countries ) ) {
        $boolean = false;
    }
    return $boolean;
}

Code goes in functions.php file of your active child theme (or active theme). It should works (untested).



Answered By - LoicTheAztec
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing