Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JarrydLong/875378df4d6ddbf22e99f707357bab1b to your computer and use it in GitHub Desktop.
Save JarrydLong/875378df4d6ddbf22e99f707357bab1b to your computer and use it in GitHub Desktop.
<?php
/**
* Apply the VAT tax if an EU country is chosen at checkout.
* This will ensure that VAT tax is applied even if a VAT tax number is applied.
*/
function mypmprovat_pmpro_tax($tax, $values, $order)
{
global $current_user, $pmpro_vat_by_country;
if(!empty($_REQUEST['vat_number']))
$vat_number = sanitize_text_field($_REQUEST['vat_number']);
elseif(!empty($_SESSION['vat_number']))
$vat_number = sanitize_text_field($_SESSION['vat_number']);
else
$vat_number = "";
//Check the billing country first. If an EU country was selected, we would have made sure it matched the billing country.
if(!empty($values['billing_country']))
$eucountry = $values['billing_country'];
elseif(!empty($_REQUEST['eucountry']))
$eucountry = sanitize_text_field($_REQUEST['eucountry']); //but you might have an eucountry set with no billing country
elseif(!empty($_SESSION['eucountry']))
$eucountry = sanitize_text_field($_SESSION['eucountry']); //ditto if you store in a session to go offsite
else
$eucountry = "";
if(!empty($values['billing_state']))
$bstate = $values['billing_state'];
elseif(!empty($_REQUEST['bstate']))
$bstate = sanitize_text_field($_REQUEST['bstate']);
elseif(!empty($_SESSION['bstate']))
$bstate = sanitize_text_field($_SESSION['bstate']);
else
$bstate = "";
$vat_rate = 0; //default to 0
//check for vat number, validate if needed, set tax rate
if(!empty($_REQUEST['vat_number_verified']) && $_REQUEST['vat_number_verified'] == "1") {
$vat_number_verified = true;
$vat_rate = pmprovat_getTaxRate($eucountry, $bstate);
} elseif(!empty($_SESSION['vat_number_verified']) && $_SESSION['vat_number_verified'] == "1") {
$vat_number_verified = true;
$vat_rate = pmprovat_getTaxRate($eucountry, $bstate);
} else {
$vat_number_verified = false;
//they didn't use AJAX verify. Verify them now.
if( empty($eucountry) )
{
$vat_rate = 0;
}
//they don't have a VAT number.
elseif(!empty($eucountry) && array_key_exists($eucountry, $pmpro_vat_by_country))
{
$vat_rate = pmprovat_getTaxRate($eucountry, $bstate);
}
}
//add vat to total taxes
if(!empty($vat_rate))
$tax = $tax + round((float)$values['price'] * $vat_rate, 2);
return apply_filters( 'pmprovat_calculated_taxes', $tax, $values, $vat_rate, $vat_number, $eucountry, $bstate );
}
add_filter("pmpro_tax", "mypmprovat_pmpro_tax", 10, 3);
/**
* Remove the existing tax calculation so that we an implement
* our own above
*/
function mypmpro_override_init_pmprotax(){
remove_filter("pmpro_tax", "pmprovat_pmpro_tax", 10, 3);
}
add_action( 'init', 'mypmpro_override_init_pmprotax' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment