Shopify Tutorials

Add Shipping Rates Calculator on Shopify Cart Page

The shipping rates calculator displays your Shipping rates calculator on cart on the cart page of your store. If a customer is logged in, then the calculator uses the customer’s default shipping address to estimate shipping rates. The Shipping Calculator Shopify works with carrier-calculated rates, manual rates, or a combination of the two.

Editing your theme code to add the shipping calculator

  • From your Shopify admin, go to Online Store > Themes.
  • Find the theme you want to edit, and then click Actions > Edit code.
  • In the Assets directory, click vendor.js. If your theme doesn’t have a vendor.js file, then click theme.js instead.
  • Shipping Rates Calculator At the very bottom of vendor.js, paste the below code. If you are editing theme.js instead, then paste the same code snippet at the very top of the file.
/**
 * Module to add a shipping rates calculator to cart page.
 *
 * Copyright (c) 2011-2016 Caroline Schnapp (11heavens.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Modified by David Little, 2016
 */
"object"==typeof Countries&&(Countries.updateProvinceLabel=function(e,t){if("string"==typeof e&&Countries[e]&&Countries[e].provinces){if("object"!=typeof t&&(t=document.getElementById("address_province_label"),null===t))return;t.innerHTML=Countries[e].label;var r=jQuery(t).parent();r.find("select");r.find(".custom-style-select-box-inner").html(Countries[e].provinces[0])}}),"undefined"==typeof Shopify.Cart&&(Shopify.Cart={}),Shopify.Cart.ShippingCalculator=function(){var _config={submitButton:"Calculate shipping",submitButtonDisabled:"Calculating...",templateId:"shipping-calculator-response-template",wrapperId:"wrapper-response",customerIsLoggedIn:!1,moneyFormat:"${{amount}}"},_render=function(e){var t=jQuery("#"+_config.templateId),r=jQuery("#"+_config.wrapperId);if(t.length&&r.length){var templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var n=Handlebars.compile(jQuery.trim(t.text())),a=n(e);if(jQuery(a).appendTo(r),"undefined"!=typeof Currency&&"function"==typeof Currency.convertAll){var i="";jQuery("[name=currencies]").size()?i=jQuery("[name=currencies]").val():jQuery("#currencies span.selected").size()&&(i=jQuery("#currencies span.selected").attr("data-currency")),""!==i&&Currency.convertAll(shopCurrency,i,"#wrapper-response span.money, #estimated-shipping span.money")}}},_enableButtons=function(){jQuery(".get-rates").removeAttr("disabled").removeClass("disabled").val(_config.submitButton)},_disableButtons=function(){jQuery(".get-rates").val(_config.submitButtonDisabled).attr("disabled","disabled").addClass("disabled")},_getCartShippingRatesForDestination=function(e){var t={type:"POST",url:"/cart/prepare_shipping_rates",data:jQuery.param({shipping_address:e}),success:_pollForCartShippingRatesForDestination(e),error:_onError};jQuery.ajax(t)},_pollForCartShippingRatesForDestination=function(e){var t=function(){jQuery.ajax("/cart/async_shipping_rates",{dataType:"json",success:function(r,n,a){200===a.status?_onCartShippingRatesUpdate(r.shipping_rates,e):setTimeout(t,500)},error:_onError})};return t},_fullMessagesFromErrors=function(e){var t=[];return jQuery.each(e,function(e,r){jQuery.each(r,function(r,n){t.push(e+" "+n)})}),t},_onError=function(XMLHttpRequest,textStatus){jQuery("#estimated-shipping").hide(),jQuery("#estimated-shipping em").empty(),_enableButtons();var feedback="",data=eval("("+XMLHttpRequest.responseText+")");feedback=data.message?data.message+"("+data.status+"): "+data.description:"Error : "+_fullMessagesFromErrors(data).join("; ")+".","Error : country is not supported."===feedback&&(feedback="We do not ship to this destination."),_render({rates:[],errorFeedback:feedback,success:!1}),jQuery("#"+_config.wrapperId).show()},_onCartShippingRatesUpdate=function(e,t){_enableButtons();var r="";if(t.zip&&(r+=t.zip+", "),t.province&&(r+=t.province+", "),r+=t.country,e.length){"0.00"==e[0].price?jQuery("#estimated-shipping em").html("FREE"):jQuery("#estimated-shipping em").html(_formatRate(e[0].price));for(var n=0;n<e.length;n++)e[n].price=_formatRate(e[n].price)}_render({rates:e,address:r,success:!0}),jQuery("#"+_config.wrapperId+", #estimated-shipping").fadeIn()},_formatRate=function(e){function t(e,t){return"undefined"==typeof e?t:e}function r(e,r,n,a){if(r=t(r,2),n=t(n,","),a=t(a,"."),isNaN(e)||null==e)return 0;e=(e/100).toFixed(r);var i=e.split("."),o=i[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+n),s=i[1]?a+i[1]:"";return o+s}if("function"==typeof Shopify.formatMoney)return Shopify.formatMoney(e,_config.moneyFormat);"string"==typeof e&&(e=e.replace(".",""));var n="",a=/\{\{\s*(\w+)\s*\}\}/,i=_config.moneyFormat;switch(i.match(a)[1]){case"amount":n=r(e,2);break;case"amount_no_decimals":n=r(e,0);break;case"amount_with_comma_separator":n=r(e,2,".",",");break;case"amount_no_decimals_with_comma_separator":n=r(e,0,".",",")}return i.replace(a,n)};return _init=function(){new Shopify.CountryProvinceSelector("address_country","address_province",{hideElement:"address_province_container"});var e=jQuery("#address_country"),t=jQuery("#address_province_label").get(0);"undefined"!=typeof Countries&&(Countries.updateProvinceLabel(e.val(),t),e.change(function(){Countries.updateProvinceLabel(e.val(),t)})),jQuery(".get-rates").click(function(){_disableButtons(),jQuery("#"+_config.wrapperId).empty().hide();var e={};e.zip=jQuery("#address_zip").val()||"",e.country=jQuery("#address_country").val()||"",e.province=jQuery("#address_province").val()||"",_getCartShippingRatesForDestination(e)}),_config.customerIsLoggedIn&&jQuery(".get-rates:eq(0)").trigger("click")},{show:function(e){e=e||{},jQuery.extend(_config,e),jQuery(function(){_init()})},getConfig:function(){return _config},formatRate:function(e){return _formatRate(e)}}}();
  • Click Save
  • In the Assets directory, click theme.js. At the very bottom of the file, paste the following code:

 

Shopify.Cart.ShippingCalculator.show( {
  submitButton: theme.strings.shippingCalcSubmitButton,
  submitButtonDisabled: theme.strings.shippingCalcSubmitButtonDisabled,
  customerIsLoggedIn: theme.strings.shippingCalcCustomerIsLoggedIn,
  moneyFormat: theme.strings.shippingCalcMoneyFormat
} );

 

  • In the Snippets directory, add a new snippet named shipping-calculator.liquid and add Shipping rates calculator on cart following code:

 

{% unless settings.shipping_calculator == 'Disabled' %}
<div id="shipping-calculator">
  <h3>{{ settings.shipping_calculator_heading | default: 'Get shipping estimates' }}</h3>
  <div>
    <p class="field">
      <label for="address_country">Country</label>
      <select id="address_country" name="address[country]" data-default="{% if shop.customer_accounts_enabled and customer %}{{ customer.default_address.country }}{% elsif settings.shipping_calculator_default_country != '' %}{{ settings.shipping_calculator_default_country }}{% endif %}">{{ country_option_tags }}</select>
    </p>
    <p class="field" id="address_province_container" style="display:none;">
      <label for="address_province" id="address_province_label">Province</label>
      <select id="address_province" name="address[province]" data-default="{% if shop.customer_accounts_enabled and customer and customer.default_address.province != '' %}{{ customer.default_address.province }}{% endif %}"></select>
    </p>
    <p class="field">
      <label for="address_zip">Zip/Postal Code</label>
      <input type="text" id="address_zip" name="address[zip]"{% if shop.customer_accounts_enabled and customer %} value="{{ customer.default_address.zip }}"{% endif %} />
    </p>
    <p class="field">
      <input type="button" class="get-rates btn button" value="{{ settings.shipping_calculator_submit_button_label | default: 'Calculate shipping' }}" />
    </p>
  </div>
  <div id="wrapper-response">
    {% comment %} Price: {{ shipping_method.price | money }} {% endcomment %}
  </div>
</div>
{% endunless %}

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20id%3D%22shipping-calculator-response-template%22%20type%3D%22text%2Ftemplate%22%3E%0A%20%20%7B%25%20raw%20%25%7D%0A%20%20%3Cwp-p%20id%3D%22shipping-rates-feedback%22%20%7B%7B%23if%20success%7D%7D%20class%3D%22success%22%20%7B%7Belse%7D%7D%20class%3D%22error%22%20%7B%7B%2Fif%7D%7D%3E%0A%20%20%7B%7B%23if%20success%7D%7D%0A%20%20%20%20%7B%7B%23if%20rates%7D%7D%0A%20%20%20%20%20%20%3Cspan%3E%20%3Cstrong%3E%20Here%20are%20some%20available%20shipping%20method%20%3C%2Fstrong%3E%3C%2Fspan%3E%3C%2Fwp-br%3E%0A%20%20%20%20%20%20%3Cul%3E%0A%20%20%20%20%20%20%7B%7B%23rates%7D%7D%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Cli%3E%7B%7Bname%7D%7D%3A%20%3Cstrong%3E%20%7B%7Bprice%7D%7D%20%3C%2Fstrong%3E%20%3C%2Fli%3E%0A%0A%20%20%20%20%20%20%7B%7B%2Frates%7D%7D%0A%20%20%20%20%20%20%3C%2Ful%3E%0A%20%20%20%20%7B%7Belse%7D%7D%0A%20%20%20%20%20%20We%20do%20not%20ship%20to%20this%20destination.%0A%20%20%20%20%7B%7B%2Fif%7D%7D%0A%20%20%7B%7Belse%7D%7D%0A%20%20%20%20%7B%7B%20errorFeedback%20%7D%7D%0A%20%20%7B%7B%2Fif%7D%7D%0A%20%20%3C%2Fwp-p%3E%0A%20%20%7B%25%20endraw%20%25%7D%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
  • Click Save
  • In the Sections directory, find cart-template.liquid. If your theme doesn’t have a cart-template.liquid file, then, in the Templates directory, find cart.liquid. Locate the closing tag, paste the following code above the tag:
{% render 'shipping-calculator' %}
  • At the very bottom of the file, Shipping rates calculator on cart paste the following code:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20theme.strings%20%3D%20%7B%0A%20%20%20%20%20%20shippingCalcSubmitButton%3A%20%7B%7B%20settings.shipping_calculator_submit_button_label%20%7C%20default%3A%20'Calculate%20shipping'%20%7C%20json%20%7D%7D%2C%0A%20%20%20%20%20%20shippingCalcSubmitButtonDisabled%3A%20%7B%7B%20settings.shipping_calculator_submit_button_label_disabled%20%7C%20default%3A%20'Calculating...'%20%7C%20json%20%7D%7D%2C%0A%20%20%20%20%20%20%7B%25%20if%20customer%20%25%7DshippingCalcCustomerIsLoggedIn%3A%20true%2C%7B%25%20endif%20%25%7D%0A%20%20%20%20%20%20shippingCalcMoneyFormat%3A%20%7B%7B%20shop.money_with_currency_format%20%7C%20json%20%7D%7D%0A%20%20%7D%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fhandlebars.js%2F4.0.10%2Fhandlebars.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22%2Fservices%2Fjavascripts%2Fcountries.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22%7B%7B%20'shopify_common.js'%20%7C%20shopify_asset_url%20%7D%7D%22%20defer%3D%22defer%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
  • Click Save
  • Config directory, settings_schema.json. Near the very bottom of the file, paste the following code before the last square bracket ] and after the last curly bracket } – make sure to include that first comma , since you’re modifying a JSON data structure:
,
  {
    "name": "Shipping Rates Calculator",
    "settings": [
      {
        "type": "select",
        "id": "shipping_calculator",
        "label": "Show the shipping calculator?",
        "options": [
          {
            "value": "Disabled",
            "label": "No"
          },
          {
            "value": "Enabled",
            "label": "Yes"
          }
        ],
        "default": "Enabled"
      },
      {
        "type": "text",
        "id": "shipping_calculator_heading",
        "label": "Heading text",
        "default": "Get shipping estimates"
      },
      {
        "type": "text",
        "id": "shipping_calculator_default_country",
        "label": "Default country selection",
        "default": "United States"
      },
      {
        "type": "paragraph",
        "content": "If your customer is logged-in, the country in his default Shipping rates calculator on cart address will be selected. If you are not sure about the  spelling to use here, refer to the first checkout page."
      },
      {
        "type": "text",
        "id": "shipping_calculator_submit_button_label",
        "label": "Submit button label",
        "default": "Calculate shipping"
      },
      {
        "type": "text",
        "id": "shipping_calculator_submit_button_label_disabled",
        "label": "Submit button label when calculating",
        "default": "Calculating..."
      },
      {
        "type": "paragraph",
        "content": "Do not forget to include the Add Shipping rates Calculator on Cart. liquid template where you want the shipping  calculator to appear. You can get the snippet here: [shipping-calculator.liquid](https:\/\/github.com\/carolineschnapp\/shipping-calculator\/blob\/master\/shipping-calculator.liquid) ."
      }
    ]
  }
  • Go to the theme editor.
  • Under Theme settings, click Shipping Rates Calculator to view and edit the Shopify Shipping Calculator settings.
    You can configure the following settings:
    • Show the Shopify Shipping Calculator? – set this to Yes to display the Shipping rates calculator on cart page, or No to hide it
    • Heading text – enter the text that will be displayed above your shipping rates calculator
    • Default country selection – choose which country will be selected by default
    • Submit button label – enter the text that will be shown on the submit button.
  • You can add styling for design to assets> theme.scss.liquid

Enjoy 🙂

Shopify Developer

Recent Posts

How to Link eBay to Shopify Store

Imagine! Seamlessly connecting the vast customer base of eBay with the robust features of your…

1 month ago

Unlock the Power of Shopify Flow: Automation Strategies for eCommerce

Let’s face it. Running an online store requires unwavering discipline. Juggling multiple tasks simultaneously is…

2 months ago

Everything You Need to Know About Shopify Liquid

There’s no denying that Shopify has taken over the world. The ecommerce platform contributes to…

2 months ago

Maximizing Revenue: 7 Best Shopify Themes for Conversion Rates that Soar

It’s true. Every marketing strategy has one common objective: to drive maximum conversion rates. If…

3 months ago

Terrific Dropshipping Business Ideas for 2024

*Sigh*. Are you tired of trying out different methods of making money online? Hear it…

3 months ago

Shopify SEO Checklist for Continued Success in 2023

When driving traffic to your Shopify store, Search Engine Optimization (SEO) is the most affordable…

3 months ago