Search code examples
phpwordpresswoocommercehook-woocommerce

Change this code to include multiple postcodes


Currently, using the following code to add a surcharge to WooCommerce if the postcode begins with "BT" but I also want to add a few more, if I change this to "BT", "IM" i get errors

function woocommerce_bt_postcode_surcharge() {

    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( $woocommerce->customer->get_shipping_country() === 'GB' ) {
        $postcode = $woocommerce->customer->get_shipping_postcode();
        if ( isset( $postcode )
             && strtoupper( substr( trim( $postcode ), 0, 2 ) ) === 'BT' ) {
            $woocommerce->cart->add_fee( 'NI Surcharge', 57, true, '' );
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_bt_postcode_surcharge' );

Solution

  • function woocommerce_bt_postcode_surcharge() {
            global $woocommerce;
    
            if (is_admin() && !defined('DOING_AJAX'))
                return;
    
            $allowed_postcodes = array('IM', 'BT');
    
            if ($woocommerce->customer->get_shipping_country() === 'GB') {
                $postcode = $woocommerce->customer->get_shipping_postcode();
                if (isset($postcode) && in_array(strtoupper(substr(trim($postcode), 0, 2)), $allowed_postcodes)) {
                    $woocommerce->cart->add_fee('NI Surcharge', 57, true, '');
                }
            }
        }
    
    add_action('woocommerce_cart_calculate_fees', 'woocommerce_bt_postcode_surcharge');