Conditional Shipping by Form Total

A user on the Gravity Forms Support Forums posted today asking if it were possible to setup a shipping fee that was only applicable if the order total was over a certain amount. As of Gravity Forms v1.6.4, this is now possible!

The form total (aka order total) may not be available for conditional logic; however, Number fields are and as of Gravity Forms v1.6.4, Number fields have been enhanced to support calculations. This tutorial will demonstrate how Gravity Form calculations work and how you can use this new feature to setup conditional shipping.

  1. The Calculated Form Total
  2. Shipping Conditional Logic
  3. Hiding the Calculated Form Total

Calculated Form Total

There may still be some situations where you need to calculate your form total manually; however, most cases can now easily be handled with this snippet: Subtotal Merge Tag

I’m going to assume you already have your form setup with products, options, etc. The next step will be to add a Number field. Open up the settings for this field and click “Enable Calculation” to reveal the “Formula” textarea.

Number Field: Calculated Form Total

Now comes the tedious part.

In order to get the form total you will need to calculate each product’s total and then add them together. To get a product’s total, you must add the product price to the product options price and then multiply this sum by the product quantity. You then add up each product’s total to get the form total.

  • Single Product with a Single Option (Product Price + Option Price) * Product Quantity
  • Single Product with Multiple Options (Product Price + Option #1 Price + Option #2 Price) * Product Quantity
  • Multiple Products ((Product #1 Price + Option #1 Price) * Product #1 Quantity) + ((Product #2 Price + Option #2 Price) * Product #2 Quantity)

For simple forms this is no problem. For larger forms… have fun.

Shipping Conditional Logic

Now that you have your Number field setup as a calculation, you’re ready to configure your Shipping field’s conditional logic. For this example, we’ll configure the Shipping field to only display if the “Calculated Form Total” is greater than 10.

Shipping Field: Conditional Logic

Hiding the Calculated Form Total

So you’ve tried it out and it’s amazing, but… you probably don’t want to leave your Calculated Form Total field visible for users to see. Just add “gf_hidden” as a CSS class for this field on the “Advanced” tab. Presto strango!

Summary

That’s a wrap! What do you think? Will you use this technique on your own forms?

Comments

  1. serhat
    serhat October 3, 2022 at 4:54 pm

    Hi, I tried to implement Gravity Wiz // Gravity Forms // Calculated Shipping using https://github.com/gravitywiz/snippet-library/blob/master/gravity-forms/gw-calculated-shipping.php

    I created 3 calculated product fields. Each field have conditional logic and calculation and have right values.

    So I want if subtotal value is lower than 999, use 135 as ‘field_id’ if subtotal value is between 1000 and 2500, use 137 as ‘field_id’ if subtotal value is bigger than 2501, use 135 as ‘field_id’

    I just try to add ‘field_id’ => $field_id instead my static value field id (135) in snippet configuration part.

    new GWCalculatedShipping( array( ‘form_id’ => 16, ‘field_id’ => $field_id, ) );

    So I changed snippet code to

    /** * Gravity Wiz // Gravity Forms // Calculated Shipping * https://gravitywiz.com/ * * Instruction Video: https://www.loom.com/share/aa10e3aceb4247528a27d1b27cc50516 * * A simple method for using a calculated product field as a shipping field. This provides the ability to use * calculations when determining a shipping price. * * Plugin Name: Gravity Forms – Calculated Shipping * Plugin URI: https://gravitywiz.com/ * Description: Use a calculated product field as a shipping field. * Author: Gravity Wiz * Version: 1.1 * Author URI: https://gravitywiz.com/ */ class GWCalculatedShipping {

    private $_orig_field = null;
    
    function __construct( $args ) {
    
        $this->_args = wp_parse_args( $args, array(
            'form_id'  => false,
            'field_id' => false,
        ) );
    
        add_filter( 'gform_pre_validation', array( $this, 'add_shipping_field' ), 9 );
        add_filter( 'gform_pre_render', array( $this, 'restore_original_field' ), 11 );
    
    }
    
    function add_shipping_field( $form ) {
    
        if ( $this->_args['form_id'] != $form['id'] ) {
            return $form;
        }
    
        // get our calc shipping field and convert it to default shipping field
        // REMINDER: PHP objects are always passed by reference
        // 
    
    
        $field = GFFormsModel::get_field( $form, $this->_args['field_id'] );
    
        // create a copy of the original field so that it can be restored if there is a validation error
        $this->_orig_field = GF_Fields::create( $field );
    
        $field->type      = 'shipping';
        $field->inputType = 'singleshipping';
        $field->inputs    = null;
    
        $field = GF_Fields::create( $field );
    
        // map calc value as shipping value
        $_POST[ "input_{$field->id}" ] = rgpost( "input_{$field->id}_2" );
    
        foreach ( $form['fields'] as &$_field ) {
            if ( $_field->id == $field->id ) {
                $_field = $field;
            }
        }
    
        return $form;
    }
    
    function field( $args = array() ) {
        return wp_parse_args( $args, array(
            'id'                 => false,
            'formId'             => false,
            'pageNumber'         => 1,
            'adminLabel'         => '',
            'adminOnly'          => '',
            'allowsPrepopulate'  => 1,
            'defaultValue'       => '',
            'description'        => '',
            'content'            => '',
            'cssClass'           => '',
            'errorMessage'       => '',
            'inputName'          => '',
            'isRequired'         => '',
            'label'              => 'Shipping',
            'noDuplicates'       => '',
            'size'               => 'medium',
            'type'               => 'shipping',
            'displayCaption'     => '',
            'displayDescription' => '',
            'displayTitle'       => '',
            'inputType'          => 'singleshipping',
            'inputs'             => '',
            'basePrice'          => '$0.00',
        ) );
    }
    
    function restore_original_field( $form ) {
    
        if ( $this->_args['form_id'] != $form['id'] || empty( $this->_orig_field ) ) {
            return $form;
        }
    
        foreach ( $form['fields'] as &$field ) {
            if ( $field['id'] == $this->_orig_field['id'] ) {
                $field = GF_Fields::create( $this->_orig_field );
                break;
            }
        }
    
        return $form;
    }
    

    }

    add_filter( ‘gform_get_input_value_16_123’, $value, 10, 4 );

    if($value < 999) {
        $field_id=135;
    } 
    

    else if ($value > 1000 && $value < 2500) { $field_id=137; } else if ($value > 2501) { $field_id=137; }

    Configuration

    new GWCalculatedShipping( array( ‘form_id’ => 16, ‘field_id’ => $field_id, ) );

    How can I achieve this code works?

    Thanks

    Reply
    1. Scott Ryer
      Scott Ryer Staff October 3, 2022 at 5:47 pm

      Hi Serhat,

      If you’re a Gravity Perks customer, we’d be happy to give you a hand with setting this up. Drop us a line on our Support form.

      You might also want to check out our Advanced Calculations perk. It adds if/elseif/else logic to calculations, which you could use in your calculated product field. That would let you achieve this without having to customize the snippet.

    1. Ryan Donovan
      Ryan Donovan May 21, 2020 at 10:03 am

      Hello Martin, The best way to handle this is to simply use multiple Shipping fields with Gravity Forms conditional logic set to show a specific Shipping field when a certain postal code is entered in another field.

  2. Kathy
    Kathy April 29, 2020 at 3:13 pm

    I’ve tried doing this but Gravity Forms won’t let me select a number field in conditional logic that is based on a calculation. Is this no longer possible? Thanks!

    Reply
    1. Ryan Donovan
      Ryan Donovan April 29, 2020 at 3:41 pm

      Hello Kathy, that is a bit of a strange one. I just tried this out and cannot recreate that issue. You can check and make sure another one of your plugins is not disabling this feature. What version of wordpress/gravity forms are you currently using?

  3. Jeroen Migneaux
    Jeroen Migneaux March 29, 2020 at 6:15 pm

    Hi,

    i’ve tried this on my website with the subtotal shortcode, but the number field doesn’t show the subtotal. Did I do something wrong?

    Thanks in advance!

    Jeroen

    Reply
    1. Ryan Donovan
      Ryan Donovan March 30, 2020 at 9:07 am

      Hello Jeroen, We have received your support ticket and will get you an answer as soon as we can. Thank you!

    1. Ryan Donovan
      Ryan Donovan February 28, 2020 at 11:22 am

      Hello Jaime, Do you by chance have a use case for this one that we could possibly give you a much more in depth answer. Thanks!

  4. Amanda Dominy
    Amanda Dominy August 24, 2016 at 4:13 am

    When I use this, the value calculated and shown to the user on the front end is correct, but the value stored in the database Entries is not?

    My setup: I have a dropdown product (MBSR Course) with 3 options, and a field (Current Exchange Rate) that I populate with a custom function.

    The calculation I’m using (on a Number field) is: {Current Exchange Rate:1} * {MBSR Course:4}

    For example, if the user selects a product with a value of 1000, and the current exchange rate is 0.0715, the total shown on the form is 343.2 (which is correct), but that same field stored in admin when the form is submitted, is 461000??

    What am I doing wrong?

    Reply
    1. David Smith
      David Smith Staff August 24, 2016 at 11:06 am

      Hi Amanda, it sounds like you’re using all default Gravity Forms functionality. If you’re using the latest version of Gravity Forms and still having issues, I would reach out to Gravity Forms support.

  5. Doug
    Doug November 28, 2015 at 5:31 am

    Hey David,

    I’m not getting this to happen for some reason. Here’s the link: http://florider.ca/purchase-form/

    Trying to set it up so that when 1 item is sold they are charged once for shipping. If they order 2 items, I need to double the shipping amount and so on. So add 38 $$ for every item purchased.

    Thanks, Doug

    Reply
    1. David Smith
      David Smith Staff November 28, 2015 at 8:21 am

      Hi Doug, it sounds like you want calculated shipping rather than conditional shipping. Try this snippet: https://gist.github.com/spivurno/7356056 You’ll just need to add a Calculation field to your form and set it as the “field_id” in the snippet config. It will automatically be converted to a shipping field on submission.

    2. Kerry
      Kerry January 21, 2016 at 11:03 am

      Great workaround… Looks like this is exactly what I need as well. Once I change the “feild_id” to be the calculation field from our form, does this new file go in my file structure at the root level, in the gravity form plugin directory or elsewhere?

      Thanks in advance.

    3. Joni Mueller
      Joni Mueller June 25, 2020 at 2:34 pm

      I am trying to do the same thing Kerry is doing but the nomenclature is confusing. When you say “add a calculation field” do you mean a shipping or quantity field? I am not sure which field to link to in the snippet. I have a crude dropdown now that is kind of on the honor system where they select the quantity of tattoo kits they order and that will get the correct shipping, but what you propose sounds less cumbersome.

    4. Ryan Donovan
      Ryan Donovan June 25, 2020 at 3:17 pm

      Hello Joni, Excellent question. This would be a calculated product field so you would add a product field and enable calculations on that field. Then you would use that field for the ‘field_id’ within the snippet. Hopefully that helps out!

    5. Joni Mueller
      Joni Mueller June 25, 2020 at 3:39 pm

      Hi, Ryan. I couldn’t get it to work because if I use a calculation in the product field, it won’t give the price. What I need should be a very simple thing to execute in the ecommerce world. Calculate shipping based on the number of items ordered. Why this is so difficult escapes me. I guess i will stick with my crude way of doing things for now since the client is not keen on spending a lot of money for a full bore ecommerce solution.

  6. Micke
    Micke September 23, 2015 at 5:08 am

    Im having issues with this. i have it setup so that when a customer chooses products with a total of greater than 1 or less than 500 the shipping shows up, and it works great BUT when the form is sumbitted even tho the total value is greater than 500 the shipping value that was hidden and not counted into the total now shows up in the total after submission and in the email sent.

    Any ideas as to why this happens?

    the form im talking about is at: http://www.peopleswellness.com/order-medlem/

    Reply
    1. micke
      micke September 25, 2015 at 8:47 am

      Issue came back, this method simply doesnt work for me, and i suspect that it has something to do with currencies and the way they are calculated when the form is submitted.

      I have set it up exacly like your example above and it works fine until you submit, the total changes and the shipping is added in despite the value being greater than the (in my chase 500) in the conditional logic

      After a lot of troubleshooting i found out that if the calculated value is above 5000 the shipping works correctly, as if when you submit the form the 500 value turns into 5000 and checks for that instead.

      Would love it if someone else had the same issue and how/if they resolved it could share the solution.

      Thanks

  7. deepak
    deepak June 9, 2015 at 7:52 am

    Hi David, I have a question and I have tried searching solution. But I was not able to find any solution so now on your mercy :P

    I don’t want to calculate shipping charges on product level, but in the cart where shipping charges will be calculated during checkout. Simple because many products can be delivered in a single shipment. I am pretty new to gravity forms, so to me it seems like ‘gravity form’ with ‘woocommerce gravity form product addon’ do not provide such option. Please enlighten me

    Reply
    1. David Smith
      David Smith Staff June 9, 2015 at 11:33 am

      Hey Deepak, this only works per form submission. You’ve have to find an alternate solution if you’re trying to do it to the WooCommerce cart.

  8. Jerem
    Jerem April 16, 2015 at 5:32 am

    Hi,

    I use Product addon with conditionnal logic as follow :

    I sell products on wholesale, but client can chose “Sample” with a radio button.

    If he choses sample, he gets a shipping fee of $2

    if he buys the product ( starts with 30 products minimum ) the shipping fee is more, but it depends on the countries he is from so i’m using the woocommerce Local Delivery and International Delivery

    When I use the method you explain, the $2 fees adds up with thr local delivery fee… which i dont want.

    How to do that ?

    Reply
    1. David Smith
      David Smith Staff April 16, 2015 at 7:30 am

      Hi Jerem, if you have specific options that should dictate the shipping pricing, you can base the conditional logic on whether those options are selected rather than the form total.

  9. Neil
    Neil February 13, 2015 at 6:36 am

    I have an order form for wines, where the shipping is calculated on a quantity basis, in increments of 12 bottles. So the shipping is not dependent on the order total, but rather total quantity of items. How would one go about getting this calculation, if at all possible?

    Reply
  10. Nick
    Nick October 31, 2014 at 11:11 am

    Hi David,

    I have stumbled across your site as the last chance saloon, before I junk WordPress and Gravity Forms for my website.

    You seem so helpful to others, perhaps you can point me to how I can do what I need, I have tried WP and GF forums and not one reply.

    I have a site which is going to allow users to order A4, A3, A2, A1 and A0 + Custom Size print online. There are price breaks for each A size with different unit costs, so 1-5 £3.50, 6-10 £3.25, 11-25 £3.00, 26-50 £2.75 and 51+ £2.50 each A4.

    So the user selects A4-A0 size types in their quantity and the total is shown plus hopefully the unit cost.

    If they pull down further to Custom Size they can input Width and Height when those boxes conditionally appear, type in the sizes to get a calculated unit cost.

    Once chosen they have the opportunity to upload their artwork with the order.

    I have tried all this in woocommerece and adding a measurement calculator add on, that did not work. I then was pointed to Gravity Forms and told it can be done there, so I purchased but have spent days and days trying to get it to do the above and I must be doing something wrong.

    Any pointers as to what parts I am supposed to use and how would really be appreciated.

    Thanks

    Nick

    Reply
    1. Nick
      Nick November 3, 2014 at 5:31 am

      Sorry, did not see reply button so am adding to thread ;-)

      Hi David,

      Thanks for the reply. So the purchase of perks would allow me to create a form which does all what I need as set out in my original question?

      Sorry, but I would need some pointers as to how to do this. I am very disheartened with WP after spending weeks trying to sort this out and purchasing over five add on’s.

      If I can do all this with your perks then I will be very happy.

      How will the form integrate with the theme cart and I also need that file uploader which is triggered after payment.

      Basically, Choose Poster size, or add in Custom size, Prices displayed and then add quantity needed which shows price plus VAT split. After the customer goes to pay they are prompted to upload print file.

      That’s it.

      Thanks

      Nick

    2. David Smith
      David Smith Staff November 3, 2014 at 8:39 am

      Gravity Perks (with the GP Conditional Pricing perk) would let you handle just the ability to price the product by the quantity ordered and by a calculated width and height. Everything else would be covered by either Gravity Forms or WooCommerce via the WooCommerce Gravity Forms Product Add-ons plugin.

    3. Nick
      Nick November 4, 2014 at 6:10 am

      Hi David,

      I have looked at the demo and docs on the page. Is there a demo area where this is working which I can set up a form please. Your example although showing the principle is quite different from my specifics. If I can try an online form that would be great. The suggestion hopefully will sort out the price breaks on the A sizes. How would I go about the Custom Size W x H input fields in a Gravity Form.

      Thanks

      Nick

  11. LV
    LV September 14, 2014 at 2:29 am

    Hi David,

    I would like to use heb calculation option as a commission calculator. Lets say someone want to sell something for €10 and writes €10 as selling price. Is it possible to automatically calculate my commission of for example 10% = €1? So that my set commission automatically appearce in a row next to the price the seller provided? If so, how? I hope you can help. Thank you so much in advance!

    Reply
    1. David Smith
      David Smith Staff September 15, 2014 at 10:05 pm

      You can set this up as a Number field with the calculation feature enabled and the formula to calculate your commission. You can then position this field to appear wherever you’d like via CSS.

    2. LV
      LV September 15, 2014 at 11:20 pm

      Thank you so much! That’s amazing!

      Can you please be so kind to tell me which code I need to use if (For example) someone who writes down an amount between €0-€1000 had to pay me 15% commission.

      Also which code do I have to use if someone writes €100 and the commissie bepens on the question they answerd before.

      I hope you can help me out.

  12. Asaf
    Asaf August 11, 2014 at 3:52 am

    Hi,

    It works great, however I’m using your better-pre-submission-confirmation and the number field is shown there even though I used gf_hidden class.

    How can I hide it from there?

    Reply
  13. Sainik Biswas
    Sainik Biswas May 8, 2014 at 7:23 am

    Hi I need some help. I have a requirement. If my item total is till rs 60 i want shipping to be rs 60, and if it is beyond rs 60, i want my shipping to be rs 40. How do I do this. I tried the method listed above but it only shows one value for the shipping field. Is it possible to dynamically change the shipping fields value based on item total. Please take a look at the form. Some help is much appreciated.

    Reply
    1. Daniel Richard
      Daniel Richard May 12, 2014 at 4:44 am

      @Sainik @David

      Was looking for a similar solution for this where if price A, show shipping_A, if price B, show shipping_B.

      No known way to accomplish this yet.

      Would still say that this is by far one of (if not, the most) elegant solutions around. Thanks again David!

      • Daniel
    2. Sainik Biswas
      Sainik Biswas May 12, 2014 at 4:55 am

      I asked Richard at Gravity Forms and he had a solution. To quote Richard “This is possible by using a calculated number field, shipping field and a HTML field containing a script using the gform_calculation_result hook. We don’t have an example on the demo site but I do have an example on my test site: http://gravitydev.wawrzyniak.me/calculated-shipping/ The shipping calculation field on that form would normally be hidden.” This solves my problem. This might solve Daniel’s problem too. Still thanks a lot David for the Sub Total Merge. :)

  14. Jack
    Jack October 18, 2013 at 5:22 am

    Hi guys,

    I’m still kind of confused by all these.

    Let say if I have a single $10 product weigh 1kg. The shipping cost would be $2.

    And what if a customer ordered 2 products, the shipping should now cost $4.

    So instead of $10 x 2 + $2 = $22, I want it to be $10 x 2 + $4 = $24.

    Any idea how to calculate this with GForm?

    Thanks in advance!

    Reply
  15. Jeremy
    Jeremy July 8, 2013 at 11:16 pm

    Ok here is how I got my equation to work. Product enable caculation {Option:8}{Number:7}{Quantity:4}

    By doing it this way the Total field becomes the Product field and the total field is not used.

    Thanks again for all the useful insight in to how Gravity Forms works. JC

    Reply
  16. Jeremy
    Jeremy July 8, 2013 at 9:05 pm

    Hi David and all viewers, I am new to gravity Forms and loving it so far. Great insight in to how the whole thing works. Thanks

    Now I have a question on how calculate a form that has 3 parts on one page and one product.

    (product+option)(quanty1)(quanty2)==(total)

    the (quanty1) field is really size. and (quanty2) is how many. do I use a (custom calculation field) instead of (Total) Or do I use Allow field to be populated dynamically then calculate total after?

    any help here would be nice. Thanks and multi readers also want to know also. Thanks again and keep up the great work. Loving it. JC

    Reply
  17. Keely
    Keely April 20, 2013 at 7:07 pm

    I just have a set of products and I tried this but it didn’t work. I don’t have options or quantities – what to do?

    Thanks

    Reply
    1. Keely
      Keely April 23, 2013 at 6:35 am

      Thanks for that David – added the snippet into my functions.php but no subtotal merge field. Oh well. Back to the drawing borad.

    2. David Smith
      David Smith Staff April 23, 2013 at 11:31 am

      Not sure why you wouldn’t be seeing the {subtotal} merge tag in the drop down; however, as long as the code is in place, you can just add the merge tag manually:

      {subtotal}

  18. don
    don December 7, 2012 at 10:55 am

    Hi David,

    Thanks for your great tutorial!

    How can we hiding the calculated Form Total, when using the merge tag: {all_fields}?

    Option {all_fields:noadmin,nohidden} doesn’t work.

    Reply
  19. Wayne
    Wayne June 18, 2012 at 9:52 pm

    Hi David, can radio options each have a price?

    for example i have a single product field (price & quantity) and two radio buttons Menu 1 and Menu 2. If a user selects Menu 1 ($65) then it should multiply the $65 for menu 1 option by the QTY in the single product field e.g. {menu1:2.1}*{product:1.3}

    Reply
  20. Wayne
    Wayne June 14, 2012 at 11:00 pm

    Thanks David, what happens say for example you have a single product field (say the price is $12 (per person) then you have a 2 menu options Menu 1 and Menu 2 (using radio buttons).

    If someone say purchase 4 $12 tickets and chooses Menu 1 ($65pp) how would you multiply the Menu 1 option price by the quantity (4)? would it be something along the lines of:

    {Single product (Quantity):1.3}*{Menu (option ):2.1}

    so that the Calculated price (sub total price) would equal $308 ($12 x 4 + $65 x 4)

    Reply
    1. David Smith
      David Smith Staff June 15, 2012 at 8:08 am

      You will want to add the product price with all of its options. You wrap this part of the equation in parenthesis so it will be calculated first. Then you multiply the product total (the product price and all of its options) by the quantity.

      There is an example of this in the calculated form total section above. Let me know if you need any further clarification. :)

  21. Wayne
    Wayne June 14, 2012 at 2:58 am

    Noob question here but what is the .2 at the end reffering too? in this string? {Simple Product (Price):1.2} i assume the 1 is the ID of the field but not sure what the .2 is

     

    Reply
    1. David Smith
      David Smith Staff June 14, 2012 at 10:18 am

      Hi Wayne, good question. Some fields in GF consist of more than one input. Checkboxes for example. Each checkbox is a different input but they’re all part of the same field. So you can target specific checkbox inputs by add a decimal after the field ID and then specifying the input ID you wish to display. So if you wanted to target the third checkbox of a checkbox field and the field ID was 12, you would write 12.3

      This same concept applies to single product fields as well. There are three possible inputs: product name, price and quantity. If the product field ID is 8, you can target the price input with 8.2.

  22. David - Diseño Web
    David - Diseño Web June 6, 2012 at 3:55 am

    Good Work.

    I’m wondering how can i make conditional calculations? For example: If a quantity is more than x, use a formula…

    Reply
    1. David Smith
      David Smith Staff June 6, 2012 at 3:15 pm

      Hi David, single product fields are not available for conditional logic; however, using a Number field configured as a calculation you can store the quantity like so: http://grab.by/e1cM

      You can then apply the conditional logic to your calculated product field based on the calculated number field like so: http://grab.by/e1cS

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.

Grab a bundle of free Gravity Forms plugins

Enter your email and receive our most popular free plugins and snippets, plus access to hundreds of others.

This field is for validation purposes and should be left unchanged.