Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active August 3, 2020 00:02
Show Gist options
  • Save spivurno/4631452 to your computer and use it in GitHub Desktop.
Save spivurno/4631452 to your computer and use it in GitHub Desktop.

This walk-through will demonstrate how to calculate and add tax to your entry total. There are two pieces to the Gravity Forms pricing puzzle (easy puzzle, huh?):

  1. the total that is calculated on the front-end as the user selects various products
  2. the total that is calculated (and validated!) in the backend

Any time you are customizing Gravity Form pricing, you'll need to make sure you implement your changes in both places.

The Front-end Total

To modify the front-end total we're going to use a Gravity Form definable function: [[gform_product_total]]. Gravity Forms will automatically check for this function and if you've defined it, it will run every time the total is updated. Here is snippet of code that defines this function for our form:

// update the "78" to the ID of your form
add_filter('gform_pre_render_78', 'add_total_script');
function add_total_script($form) {
    ?>
    
    <script type="text/javascript">
    function gform_product_total(formId, total){
        var tax = ((20 * total) / 100); // update the "20" to the desired tax percentage;
        tax = Math.round(tax*100)/100; //rounding tax to 2 decimal digits
        return total + tax;
    }
    </script>
    
    <?php
    return $form;
}

You'll notice that we're using the gform_pre_render hook to output our script block to the page. There are multiple ways to accomplish this. The gform_pre_render hook is just one of the ways.

Quick Tip So what's up with the random opening and closing tags in the above snippet? With PHP you can indicate that you'd like to stop executing PHP code and start outputting HTML directly to the page. This makes it a lot easier to output large chunks of HTML/JS code without having to echo it via PHP.

Inside the script block we define our gform_product_total function. Our first task is calculating the tax. In our case, we're adding a 20% tax. If you are also doing a percentage tax, just update the "20" to the tax percentage your situation requires. If your tax requirements are different, feel free to use any equation to determine the tax.

Now that we have our tax, we need to return the total plus the tax to Gravity Forms. GF will handle updating the total field (if you have a total field) on your form with this modified total.

The Back-end Total

Next up: the back-end total. Remember, customizations made to pricing fields on the front-end almost always need to be supported in the back-end. This means more custom code. On the front-end we've updated our total with the 20% tax. Now let's make sure it gets added in the back-end as well.

// update the "78" to the ID of your form
add_filter('gform_product_info_78', 'update_product_info', 10, 3);
function update_product_info($product_info, $form, $entry) {
    
    $total = get_total($product_info);
    $tax = (20 * $total) / 100; // update the "20" to the desired tax percentage
    $tax = round($tax, 2); //rounding to 2 decimal digits

    $product_info['products']['tax'] = array(
        'name' => 'Tax', // name that will appear in PayPal and pricing summary tables 
        'price' => $tax, // amount of total tax
        'quantity' => 1
        );
    
    return $product_info;
}

function get_total($products) {

    $total = 0;
    foreach($products["products"] as $product){

        $price = GFCommon::to_number($product["price"]);
        if(is_array($product["options"])){
            foreach($product["options"] as $option){
                $price += GFCommon::to_number($option["price"]);
            }
        }
        $subtotal = floatval($product["quantity"]) * $price;
        $total += $subtotal;

    }

    $total += floatval($products["shipping"]["price"]);

    return $total;
}

Hm, that looks like a bit more code than we needed for the front-end, huh? Don't worry. It's just as easy. The first step is to hook into the gform_product_info hook. This hook will pass whatever function we tie to it an array of all the form's product information, including how many of each item were selected on the current order. With this in mind, here's a step by step of how we're going to use that product information.

$total = get_total($product_info['products']);

We're using the get_total() custom function to retrieve the total of the current products. You'll see where we've defined this function at the bottom of the snippet. It's important to note that this is not an official Gravity Forms function; just a custom helper function that aids us in this scenario. This function will return the total based on the selected products and their base prices.

$tax = (20 * $total) / 100; // update the "20" to the desired tax percentage

Now that we have the total we can calculate the tax. Again, if you are also using a percentage tax, just update the "20" with your percentage. If not, update the equation to get the tax result you require.

$product_info['products']['tax'] = array(
    'name' => 'Tax', // name that will appear in PayPal and pricing summary tables 
    'price' => $tax, // amount of total tax
    'quantity' => 1
    );

Now, remember how the gform_product_info hook passes all the form product information in the $product_info array? Well, we can actually customize the product information in this array before returning it!

In the above snippet, we're simply adding a new product titled "Tax" and setting the price to the calculated tax price we determined in the previous step. Since we calculated our tax on the order total, we can set the quantity to "1" so the Tax product is only applied once. Now we just return the modified $product_info array and Gravity Forms takes care of the rest.

Summary

Now that we have our front-end and back-end modifications in place, anytime a new entry is submitted, Gravity Forms will automatically handle displaying the adjusted total to the user on the front-end, sending that adjust total on to PayPal (if you're using the Gravity Forms PayPal Add-on with this form) and record the adjusted total as part of entry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment