WooCommerce Local Free Shipping Class

This file contains a PHP class that integrates with WooCommerce to provide free shipping for products that match the customer's local area zip code. It adds a new field to the product's shipping options for entering a local zip code and applies free shipping for matching products during cart calculations.

<?php if (!class_exists("Cwpai_Local_Free_Shipping")) { class Cwpai_Local_Free_Shipping { public function __construct() { add_action("woocommerce_product_options_shipping", [$this, "cwpai_add_local_zip_field"]); add_action("woocommerce_process_product_meta", [$this, "cwpai_save_local_zip_field"], 10, 2); add_action("woocommerce_cart_calculate_fees", [$this, "cwpai_apply_free_shipping"], 20); add_action('woocommerce_add_to_cart', [$this, 'cwpai_add_to_cart_action']); } public function cwpai_add_local_zip_field() { echo '<div class="options_group">'; woocommerce_wp_text_input([ "id" => "cwpai_local_zip", "label" => __("Local Zip", "codewp"), "desc_tip" => "true", "description" => __("Enter the local zip code for free shipping.", "codewp"), ]); echo "</div>"; } public function cwpai_save_local_zip_field($post_id) { if (isset($_POST["cwpai_local_zip"])) { $local_zip = sanitize_text_field($_POST["cwpai_local_zip"]); if (!empty($local_zip)) { update_post_meta($post_id, "cwpai_local_zip", $local_zip); } } } public function cwpai_apply_free_shipping() { $customer_zip = WC()->customer->get_shipping_postcode(); foreach (WC()->cart->get_cart() as $cart_item) { $product_id = $cart_item['product_id']; $product_local_zip = get_post_meta($product_id, 'cwpai_local_zip', true); if ($customer_zip === $product_local_zip) { WC()->cart->add_fee(__('Free Local Shipping', 'codewp'), -WC()->cart->get_shipping_total()); $this->cwpai_add_shipping_notice(); break; } } } public function cwpai_add_shipping_notice() { wc_add_notice(__('You are eligible for Free Local Shipping!', 'codewp'), 'success'); } public function cwpai_add_to_cart_action() { $this->cwpai_apply_free_shipping(); } } new Cwpai_Local_Free_Shipping(); } ?>

Frequently Asked Questions

It's a PHP class for WooCommerce that provides free shipping to local customers based on zip codes.