You may wish to charge an additional fee based on the user’s postcode. This solution shows how you can add a £5 fee (the currency will be whatever you have set it in your WooCommerce Settings) depending on what postcode is entered in the billing postcode field. If you would like the fee to be applied based on the shipping postcode, simply change “billing” to “shipping” in the code snippet. Amend the array of postcodes as needed – these are postcodes which are not charged a fee. You may also change the fee amount – simply change the 5 to whatever you like! Ultimately, the code snippet looks at the first two characters the customer has entered in the field. It then compares these two characters to the list. If there is a match, the user defined fee is not charged. If there is not a match, the customer checks out as normal without paying a fee based on the postcode entered.
/**
* Snippet Name: Add a order fee based on the customer postcode at the WooCommerce checkout.
* Snippet Author: ecommercehints.com
*/
add_action( 'woocommerce_cart_calculate_fees', 'ecommercehints_postcode_fee', 25 );
function ecommercehints_postcode_fee() {
// An array of postcodes which are not charged the fee
$postcodes = array(
'DD', 'DA', 'CW', '', ' ',
);
// Get first two charcters from Billing Postcode field on checkout
$postcode = substr(WC()->customer->get_billing_postcode(),0,2);
// If first two character from billing postcode field does not equal a postcode from the above list...
if (!in_array( strtoupper( $postcode ), $postcodes ) ) {
// Add an aditional cost called Postcode fee which is the value of 5
WC()->cart->add_fee( 'Postcode fee', 5 );
}
}