The [gravitymath] shortcode
The [gravitymath] shortcode from GravityMath calculates a formula and prints the result. The formula can use numbers you type, the values of one Gravity Forms entry, or the values of every entry in a form or a View.
Pure math calculations #
Format: [gravitymath] 3 * 7 [/gravitymath]
A formula with only numbers, functions, and constants needs no form or View, and works anywhere on your site.
Here’s a basic example:
[gravitymath] 2 * 300 [/gravitymath]Returns: 600
You can also use constants and functions:
[gravitymath] PI / avg(7, 8, 9) [/gravitymath]Returns: 0.39269908169872
The full list is under Supported math functions and constants.
The formula can also go in the formula parameter:
[gravitymath formula="pow( 5, 2 )" /]Returns: 25 (5^2)
To set the number of decimal places, use the decimals parameter:
[gravitymath decimals="0"] PI [/gravitymath]Returns: 3
Calculations on Gravity Forms data #
A formula can use the values of one entry, or the values of every entry in a form.
Calculations for a single entry
Format: [gravitymath scope="entry" id="{entry_id}"]
To calculate with the values of one entry, set the scope parameter to entry and id to the entry’s ID. Field values go in the formula as merge tags.
Display the value of a single numeric field:
[gravitymath scope="entry" id="123"] {Number:5} [/gravitymath]Using math functions:
[gravitymath scope="entry" id="123"]
avg( 0, {Number:5} )
[/gravitymath]Using multiple field values:
[gravitymath scope="entry" id="123"] sum( 1, 5, 10, 20, {Number:5}, {OtherNumber:6} ) [/gravitymath]Calculations for all entries in a form
Format: [gravitymath scope="form" id="{form_id}"]
To calculate over every entry of a form, set the scope parameter to form and id to the form’s ID. Field values go in the formula as merge tags.
There are also special modifiers you can add to the Gravity Forms merge tags to fetch different values:
:sum: The sum of the field’s values. A merge tag with no modifier gives the sum too.:max: The highest value.:min: The lowest value.:avg: The average of the field’s values. Entries where the field is empty are left out.:count: The number of entries with a value in the field. Entries where the field is empty are left out.
Calculate the sum of field values:
[gravitymath scope="form" id="9"] {Number:5:sum} [/gravitymath]Count the entries with a value in a field:
[gravitymath scope="form" id="9"] {Number:5:count} [/gravitymath]Calculate the average value for a field:
[gravitymath scope="form" id="9"] {Number:5:avg} [/gravitymath]Using [gravitymath] inside a View #
Inside a View, the [gravitymath] shortcode goes in a Custom Content field or widget.
A calculation in a View can cover every entry in the View, the entries visible on the current page, or the current entry.
Calculations for all entries in a View
Format: [gravitymath scope="view" id="{View ID}" secret="{View secret}"]
To calculate over every entry of a View, set the scope parameter to view and id to the View’s ID.
Calculate the sum of field values for all entries in a View:
[gravitymath scope="view" id="27" secret="abc123"] {Number:5:sum} [/gravitymath]When the View has Enhanced Security on, the default for new Views, the shortcode needs the secret attribute with the View’s secret.
Calculations for the visible entries in a View
Format: [gravitymath scope="visible"]
To calculate over the entries visible on the current page of a View, set the scope parameter to visible. This works in a Custom Content widget on the View, and not in a Custom Content field, in a shortcode placed on the page around the View, or in a View with the DataTables layout. The result changes with the entries the page shows.
Display the total number of sales:
[gravitymath scope="visible"] {Sales:12:count} [/gravitymath]Calculate total revenue:
[gravitymath scope="visible" decimals="2"] {Product:3} + {Another Product:4} [/gravitymath]Calculations for the current entry in a View
Format: [gravitymath scope="entry"]
To calculate with the current entry, set the scope parameter to entry and leave out id. This works in a Custom Content field, and not in a Custom Content widget.
Example:
[gravitymath scope="entry"] {Number:5} * 5 [/gravitymath]Calculating summaries with filters #
The filter parameter limits a calculation to the entries that match a field value. It works with scope="view", scope="form", and scope="visible".
This adds up field 4 for the entries of form 9 where field 3 is Yes:
[gravitymath scope="form" id="9" filter="filter_3=Yes"] {Credits:4:sum} [/gravitymath]The filter value is built from these parts, joined with &, as in filter="filter_3=Yes&op_3=isnot&limit=10":
filter_N: The value to match, where N is the ID of the field, entry attribute, or meta key, such asfilter_3=Yes.op_N: Howfilter_Nis compared:is(the default),isnot,contains,notcontains,gt(greater than), orlt(less than).limit: The number of entries to calculate over. The default,0, uses every matching entry.
Each key is read once: when the same key appears twice, GravityMath uses only the last one. For a second condition on the same field, put the form ID and a colon before the field ID in that pair, as in filter_9:4 and op_9:4. This needs GravityMath 2.12.3 or later. This adds up field 4 for the entries where it is more than 10 and less than 20:
[gravitymath scope="form" id="9" filter="filter_4=10&op_4=gt&filter_9:4=20&op_9:4=lt"] {Credits:4:sum} [/gravitymath]With scope="view" or scope="visible", use the ID of the View’s form. For ranges of entry dates, see Sum GravityMath values for today, a custom date range, or a rolling window.
Math filters: targeting a specific field value with [gravitymath] has more examples, including choice fields and Date fields.
Nesting shortcodes #
You can also nest multiple shortcodes to create more complex calculations. This also allows you to use data from different Gravity Forms in one single equation. Here’s an example:
[gravitymath]
[gravitymath2 scope="form" id="11"] {Product:1} * {quantity:1} [/gravitymath2] + [gravitymath2 scope="form" id="4"] {Product:2} * {quantity:2} [/gravitymath2]
[/gravitymath]Nested calculations in GravityMath has more examples.
Shortcode parameters #
decimals: The number of decimals to display. Without it, the result shows the decimals the calculation returns.format: Set torawto display the number unformatted. Otherwise the number is formatted with WordPress’number_format_i18n()function.formula: The formula, as an alternative to writing it between the shortcode tags.debug: Set totrueto show administrators and editors a report of the formula and its errors after the page’s content. Debugging calculations in GravityMath explains the report.filter: Used to target a specific field value. Works withscope="view",scope="form", andscope="visible". Chain more than one condition with&, for examplefilter="filter_5=Yes&filter_7=Spring"; an entry has to match every condition to be included. A second condition on the same field needs the form ID before the field ID, as shown in Calculating summaries with filters.default_value: A number to use in place of an empty field value when the calculation reads one entry, such asdefault_value="0". The default,skip, prints nothing when a field in the formula is empty.notices: Display notices to visitors when the formula has warnings or errors. Passtrueto enable. (Default:false.) Three filters change the notices:gravityview/math/accuracy_messagechanges the warning notice. (Default: * Results may not be accurate.)gravityview/math/no_results_messagechanges the error notice. (Default: ** No Results Currently Available.)gravityview/math/admin_noticechanges the admin notice. (Default: You can only see this message because you are logged in and have permissions.)
Parameters for calculations on Gravity Forms data
id: The ID of the form, entry, or View, depending onscope.scope: What the merge tags read. Without a scope, the shortcode does pure math.form: Every entry of the form inid.entry: One entry. Needsid, except in a Custom Content field, where it uses the row’s entry.visible: The entries visible on the current page of the View. Works only in a Custom Content widget, and not with DataTables.view: Every entry of the View inid.
Supported math functions and constants #
These functions and constants work in every scope.
Functions
abs(): Returns the absolute value of a number.acos(): Returns the arccosine (in radians) of a number.asin(): Returns the arcsine (in radians) of a number.atan(): Returns the arctangent (in radians) of a number.avg( num1, num2, etc ): Returns the mean of the numbers.avg( 3, 9, 27 )returns13(39 divided by 3).ceil(): Returns the smallest integer greater than or equal to a number.ceil( 10.284742 )returns11.cos(): Returns the cosine of a number.count(): Returns how many numbers are passed.count( 1, 2, 3, 4 )returns4.deg2rad(): Converts degrees to radians.exp(): Returns e to the power of the number, where e is Euler’s number, the base of the natural logarithm.floor(): Returns the largest integer less than or equal to a number.log( number, base ): Returns the logarithm of a number in the given base. Without a base, it uses base 10:log( 100 )returns2, andlog( 8, 2 )returns3.max( num1, num2, etc ): Returns the largest of the numbers.min( num1, num2, etc ): Returns the smallest of the numbers.pow( base, exponent ): Returns the base raised to the exponent.rad2deg(): Converts radians to degrees.round( number, precision ): Rounds a number toprecisiondigits after the decimal point.precisioncan be zero (the default) or negative:round( 3.14159, 2 )returns3.14, andround( 1234, -2 )returns1,200.sin(): Returns the sine of a number.sqrt(): Returns the square root of a number.sum( num1, num2, etc ): Returns the sum of the numbers.
Constants
PI: π (3.1415926535898).PI_2: π divided by 2 (1.5707963267949).PI_4: π divided by 4 (0.78539816339745).E: Euler’s number (2.718281828459).SQRT_PI: The square root of π (1.7724538509055).SQRT_2: The square root of 2 (1.4142135623731).SQRT_3: The square root of 3 (1.7320508075689).LN_PI: The natural logarithm of π (1.1447298858494).
Math function examples
[gravitymath]
ceil( ( 51 * 2 ) + ( 15 / 2 ) )
[/gravitymath]Returns 110: ( 51 * 2 ) + ( 15 / 2 ) equals 109.5, and ceil() rounds it up to the next integer.
[gravitymath]
round( 42.8 )
[/gravitymath]Returns 43, because .8 rounds up.
Notes on shortcode use #
General things to know
- Decimals need a leading number:
50 + .5prints nothing. Write50 + 0.5. - For a price, add
:priceto the merge tag, which turns the currency format (with a symbol such as $) into a number:- Total fields:
{Total:32}becomes{Total:32:price}. - Product fields:
{Product Name (Price):28.2}becomes{Product Name (Price):28:price}. Remove the.2from the field number (28.2becomes28).
- Total fields:
- Parentheses can be nested as deep as you need:
( 1 + 2 ) + ( 3 / ( 4 * ( 5 + 6 ) ) )works. - Extra spaces in the formula are fine, such as
[gravitymath] avg( ( 100 / 3747 ), ( 48672 * 2746 ) ) [/gravitymath].
Mathematical precision
The precision of the math functions is not exact for numbers with many decimal digits. The math library uses PHP’s float type, which has a precision of roughly 14 decimal places. The Floating-Point Guide explains why.
Without the decimals parameter, the shortcode limits results to 16 decimal places. The gravityview/math/precision filter changes or removes that limit:
// Turn off the limit altogether
add_filter( 'gravityview/math/precision', '__return_false' );
// Or you can modify the precision limit (here, to 14)
add_filter( 'gravityview/math/precision', function() { return 14; } );Counting the entries that match a filter
The {entry_count} merge tag ignores the filter parameter. GravityMath replaces it with the number of entries in the whole form with scope="form", or in the View with scope="view".
To count only the entries that match the filter, use the :count modifier on a field from the form in the id parameter. :count leaves out entries where that field is empty, so pick a field that every entry has a value in, such as a required field or the field you filter on.
This prints the number of entries in form 32, whatever the filter:
[gravitymath scope="form" id="32" filter="filter_7=Some Value"] {entry_count} [/gravitymath]This prints the number of entries where field 7 is Some Value:
[gravitymath scope="form" id="32" filter="filter_7=Some Value"] {Field:7:count} [/gravitymath]Merge tags for another form in a Custom Content field
In a GravityView Custom Content field, GravityView fills in merge tags with the values of the row’s entry before the shortcode runs. A merge tag meant for another form is filled in too when the View’s form has a field with the same ID, and the shortcode then prints nothing. Using GravityMath inside a GravityView Custom Content field shows how to keep those merge tags for GravityMath.