Skip to content

Instantly share code, notes, and snippets.

@shameemreza
Created November 5, 2025 16:18
Show Gist options
  • Select an option

  • Save shameemreza/4ac81e542c25cf399e493fb3b96bd05a to your computer and use it in GitHub Desktop.

Select an option

Save shameemreza/4ac81e542c25cf399e493fb3b96bd05a to your computer and use it in GitHub Desktop.
Applies a percentage-based import tariff to shipping costs for orders going to the United States. Code based on: https://woocommerce.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/#section-3
/**
* Add US tariff surcharge to shipping costs.
*
* Custom implementation to apply US tariffs on shipping charges
* to work alongside the WooCommerce Customs Fees plugin.
*
* @since 1.0.0
* @author Shameem Reza
*/
/**
* Add US shipping tariff as a surcharge.
*
* @since 1.0.0
* @return void
*/
function add_us_shipping_tariff_surcharge() {
// Skip in admin unless doing AJAX.
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Check if WooCommerce is active and cart exists.
if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
return;
}
// Define target countries and tariff rate.
$target_countries = array( 'US' );
$tariff_rate = 0.25; // 25% tariff - adjust as needed.
// Get customer shipping country.
$customer_country = WC()->customer ? WC()->customer->get_shipping_country() : '';
// Check if tariff applies to this country.
if ( ! in_array( $customer_country, $target_countries, true ) ) {
return;
}
// Get shipping total.
$shipping_total = WC()->cart->get_shipping_total();
// Only add fee if there's shipping cost.
if ( $shipping_total > 0 ) {
$tariff_amount = $shipping_total * $tariff_rate;
// Add the fee (false = not taxable).
WC()->cart->add_fee(
__( 'US Import Tariff (Shipping)', 'woocommerce' ),
$tariff_amount,
false,
''
);
}
}
add_action( 'woocommerce_cart_calculate_fees', 'add_us_shipping_tariff_surcharge', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment