Using Gravity Forms ‘gform_calculation_formula’ PHP filter

The gform_calculation_formula Gravity Forms PHP function/filter/action allows you to dynamically modify the formula of a number field calculation or calculated product field.

Usage

add_filter('gform_calculation_formula', 'my_custom_function', 10, 4);
function my_custom_function($formula, $field, $form, $entry) {
    // your custom code here
    return $formula;
}

Parameters

  • $formula (string) – The calculation formula.
  • $field (Field Object) – The calculation field currently being processed.
  • $form (Form Object) – The form currently being processed.
  • $entry (Entry Object) – The entry currently being processed.

More information

See Gravity Forms Docs: gform_calculation_formula

Examples

Add a fixed value to the formula

In this example, we will add a fixed value of 5 to the formula when the form ID is 10 and the field ID is 3.

add_filter('gform_calculation_formula', 'add_fixed_value', 10, 4);
function add_fixed_value($formula, $field, $form, $entry) {
    if ($form['id'] == 10 && $field->id == 3) {
        $formula .= '+5';
    }
    return $formula;
}

Multiply the formula by a percentage

In this example, we will multiply the formula by 1.2 (120%) when the form ID is 5 and the field ID is 2.

add_filter('gform_calculation_formula', 'multiply_by_percentage', 10, 4);
function multiply_by_percentage($formula, $field, $form, $entry) {
    if ($form['id'] == 5 && $field->id == 2) {
        $formula .= '*1.2';
    }
    return $formula;
}

Apply a discount based on a coupon code

In this example, we will apply a 10% discount to the formula if a specific coupon code is entered in field ID 4.

add_filter('gform_calculation_formula', 'apply_coupon_discount', 10, 4);
function apply_coupon_discount($formula, $field, $form, $entry) {
    if ($form['id'] == 8 && $field->id == 1 && $entry[4] == 'DISCOUNT10') {
        $formula .= '*0.9';
    }
    return $formula;
}

Modify the formula based on a specific date

In this example, we will double the formula if the form is submitted on or after May 1st, 2023.

add_filter('gform_calculation_formula', 'double_formula_on_date', 10, 4);
function double_formula_on_date($formula, $field, $form, $entry) {
    $current_date = strtotime('today');
    $promo_start_date = strtotime('2023-05-01');

    if ($current_date >= $promo_start_date) {
        $formula .= '*2';
    }
    return $formula;
}