Skip to content

Instantly share code, notes, and snippets.

@vishalkakadiya
Created June 25, 2017 17:55
Show Gist options
  • Save vishalkakadiya/7a677135a0a95d3a22218f2d87b2e444 to your computer and use it in GitHub Desktop.
Save vishalkakadiya/7a677135a0a95d3a22218f2d87b2e444 to your computer and use it in GitHub Desktop.
WooCommerce snippets to calculate tax/shipping based on country code.
<?php
if ( ! function_exists( 'vk_get_tax_cost_by_country' ) ) {
/**
* Get tax cost by country code.
*
* @param string $country_code Code of country.
* @param int $total Cart total.
*
* @return int Cost of tax.
*/
function vk_get_tax_cost_by_country( $country_code, $total ) {
$tax_rate = 0;
$tax = 0;
$available_tax_rates = WC_Tax::find_rates( array( 'country' => $country_code ) );
if ( ! empty( $available_tax_rates ) ) {
foreach ( $available_tax_rates as $available_tax_rate ) {
$tax_rate = $available_tax_rate['rate'];
break;
}
$tax = ( $tax_rate / 100 ) * $total;
$tax = round( $tax, 2 );
}
return $tax;
}
}
if ( ! function_exists( 'vk_get_shipping_cost_by_country' ) ) {
/**
* Get shipping cost by country code.
*
* @param string $country_code Code of country.
* @param int $quantity Total cart quantity.
*
* @return int Cost of shipping.
*/
function vk_get_shipping_cost_by_country( $country_code, $quantity ) {
$shipping_cost = 0;
if ( class_exists( 'WC_Shipping_Zones' ) ) {
$all_zones = WC_Shipping_Zones::get_zones();
if ( ! empty( $all_zones ) ) {
foreach ( $all_zones as $zone ) {
if ( ! empty( $zone['zone_locations'] ) ) {
foreach ( $zone['zone_locations'] as $code ) {
if ( $country_code === $code->code ) {
if ( ! empty( $zone['shipping_methods'] ) ) {
foreach ( $zone['shipping_methods'] as $flat_rate ) {
$shipping_cost = str_replace( ' * [qty]', '', $flat_rate->cost );
if ( strpos( $flat_rate->cost, '[qty]' ) !== false ) {
$shipping_cost = ( $shipping_cost * $quantity );
}
break;
}
}
}
}
}
}
}
}
return $shipping_cost;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment