Adapt shipping surcharge code [closed]

Here’s an untested modified version of your code:

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( 'Surcharge', 35, true, '' );
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_bt_postcode_surcharge' );

Note that

  • I’ve copied your use of the $woocommerce global, but if I was writing this myself I’d use WC() instead
  • I’ve also copied the true flag from the add_fee line, which means that the surcharge is taxable. Is that what you meant? See the add_fee documentation.
  • and if I were a customer I’d probably appreciate a better explanation than just ‘Surcharge’, since this seems a rather large amount (but then I don’t know what you’re selling or why you’re charging this)
  • I also don’t know how or when this event gets called. If it can get called multiple times for the same cart then you might need to
    • check whether or not the fee already existed before adding it again, although it’s also possible that the cart itself will deduplicate fees
    • spot that you’ve added the fee but the customer has now changed their delivery address so that it’s no longer BT, and remove the fee.

And here’s a version extended to cover more postcodes:

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 ) ) {
            $prefix = strtolower( substr ( trim ( $postcode ), 0, 2 ) );
            // 35 surcharge for BT or IV
            if ( $prefix === 'BT' || $prefix === 'IV' ) {
                $woocommerce->cart->add_fee( 'Surcharge', 35, true, '' );
            }
            // 50 surcharge for RG
            if ( $prefix === 'RG' ) {
                $woocommerce->cart->add_fee( 'Surcharge', 50, true, '' );
            }
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_bt_postcode_surcharge' );