Zip code starts with issue

Solved
m_waqas
Trailblazer
164 36 48

Hi there,

I want to show/hide a few shipping methods based on the ZIP code entered at the checkout. I am trying to write a shipping script for that but facing an issue that I can't check if a Zipcode starts with some value or not. So, for example, if a customer enters the ZIP code "BT1 1BG" I want to check if it starts with "BT" or not.

According to my knowledge, I can only check the exact match or partial match but in case of the partial match it would return true if "BT" exists anywhere in the ZIP code, for example, "EC1A 1BT"; and I don't want this result. I tried to use "start_with" method, but it is not working in the Shipping script.

Any solution or workaround would be much appreciated!

Thanks!

- Was my reply helpful? Click Like and Accept as Solution
- Want to implement a custom solution? Feel free to contact me at waqas4346@gmail.com
0 Likes

This is an accepted solution.

Hi @m_waqas,

I am wondering if you just forgot the "?" (question mark) at the end of the start_with? method. Because when you generate a sample shipping script for hiding methods, it actually uses the start_with? method:

Screen Shot 2021-03-09 at 12.55.07 AM.png

 

Given that, here is the script that seemed to work for me. I also added a hash in the beginning to make it easier to add new use cases. 

# make a mapping of which shipping methods to remove based on zip prefixes
mapping = { 
  'BT' => 'USPS', 
  '16' => 'FEDEX_EXPRESS'
}

# empty array where we will store our removed zip codes
removed_zips = []

# store the customer's zip code
customer_zip = Input.cart.shipping_address.zip

# step through our map and test each one, add to our list of removals if matching
mapping.each do |set|
  removed_zips << set[1] if (customer_zip.upcase.start_with? set[0])
end

# use our removal list while stepping though passed in shipping rates
Output.shipping_rates = Input.shipping_rates.delete_if do |shipping_rate|
  removed_zips.each do |zip|
    shipping_rate.name.upcase.start_with?(zip)
  end
end

 

If that worked for you, feel free to mark the solution as accepted. 

Thanks!
Matthew 

Playwright | Create Shopify Scripts without writing code | https://playwrightapp.com
- Was my reply helpful? Please Like and Accept Solution.
- Need help with a custom Shopify script? Email me at matthew@playwrightapp.com