index.php

WooCommerce Tax-Exempt Coupon Manager

This WordPress snippet adds functionality to WooCommerce allowing store owners to create coupons that can make the cart tax-exempt if the customer's billing address is in certain provinces. It integrates into the WooCommerce coupon settings, providing a new field to select tax-exempt provinces.

<?php /** * Class for managing tax-exempt coupons in WooCommerce. */ class CodeWp_Tax_Exempt_Coupon { private $meta_key = "cpwai_tax_exempt_provinces"; public function __construct() { add_action( "woocommerce_coupon_options", [$this, "addTaxExemptField"], 10, 2 ); add_action( "woocommerce_coupon_options_save", [$this, "saveTaxExemptField"], 10, 2 ); add_action( "woocommerce_before_calculate_totals", [$this, "applyTaxExemption"], 10 ); } public function addTaxExemptField($coupon_id, $coupon) { $tax_exempt_provinces = get_post_meta( $coupon_id, $this->meta_key, true ); ?> <p class="form-field"> <label for="cpwai_tax_exempt_provinces"><?php esc_html_e( "Tax Exempt Provinces", "codewp" ); ?></label> <select id="cpwai_tax_exempt_provinces" name="cpwai_tax_exempt_provinces[]" class="wc-enhanced-select" multiple> <?php foreach ( WC()->countries->get_states("CA") as $code => $name ): ?> <option value="<?php echo esc_attr( $code ); ?>" <?php selected( in_array($code, (array) $tax_exempt_provinces) ); ?>> <?php echo esc_html($name); ?> </option> <?php endforeach; ?> </select> </p> <?php } public function saveTaxExemptField($post_id, $coupon) { if (isset($_POST["cpwai_tax_exempt_provinces"])) { $tax_exempt_provinces = array_map( "sanitize_text_field", $_POST["cpwai_tax_exempt_provinces"] ); update_post_meta($post_id, $this->meta_key, $tax_exempt_provinces); } else { delete_post_meta($post_id, $this->meta_key); } } public function applyTaxExemption($cart) { if (is_admin() && !defined("DOING_AJAX")) { return; } if (did_action("woocommerce_before_calculate_totals") >= 2) { return; } $applied_coupons = $cart->get_applied_coupons(); $tax_exempt = false; foreach ($applied_coupons as $coupon_code) { $coupon = new WC_Coupon($coupon_code); $tax_exempt_provinces = get_post_meta( $coupon->get_id(), $this->meta_key, true ); if ( in_array( WC()->customer->get_billing_state(), (array) $tax_exempt_provinces ) ) { $tax_exempt = true; break; } } if ($tax_exempt) { foreach ($cart->get_cart() as $cart_item_key => $cart_item) { $cart_item["data"]->set_tax_status("none"); } $cart->set_total_tax(0); } } } new CodeWp_Tax_Exempt_Coupon(); ?>

Frequently Asked Questions

The plugin allows WooCommerce coupons to grant tax exemptions based on the customer's billing province.