The [gravitymath] Shortcode
In order to use the [gravitymath] shortcode, you must have GravityMath installed on your website.
The [gravitymath]
shortcode allows you to perform advanced math calculations on your website. With [gravitymath]
, you can:
- Perform pure math calculations
- Perform calculations using data collected via Gravity Forms
- Perform calculations on entry data in a View created with GravityView
The [gravitymath]
shortcode is very powerful. There’s a lot you can do with it. In this article, we'll give you a comprehensive overview of how to use [gravitymath]
, complete with practical examples where applicable. To help make this doc easier to navigate, we’ve created a table of contents with clickable anchor links that will take you directly to the relevant sections.
Table of contents:
- Pure Math Calculations
- Calculations Using Gravity Forms Data
- Using [gravitymath] Inside a View
- Calculating Summaries Using Filters
- Nesting shortcodes
- All Shortcode Parameters
- All Supported Math Functions and Constants
- Notes on Shortcode Use
Pure Math Calculations
Format: [gravitymath] 3 * 7 [/gravitymath]
Pure math calculations don't require GravityView or Gravity Forms!
You can perform pure calculations anywhere on your website. When performing pure math calculations, there should be no other text in the formula (i.e., no Gravity Forms merge tags), just math!
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: 75.398223686
Note: Scroll down to the end for a list of supported functions and constants.
You can also define your math equation using the formula
parameter, instead of placing in between the shortcodes, like this:
[gravitymath formula="pow( 5, 2 )" /]
Returns: 25
(5^2)
If you want to specify the number of decimal places, use the decimals
parameter:
[gravitymath decimals="0"] PI [/gravitymath]
Returns: 3
As you can see, anything inside the shortcode (or defined using the formula
shortcode parameter) is processed as a mathematical equation and is calculated.
Calculations Using Gravity Forms Data
Using the [gravitymath]
shortcode, you can perform advanced calculations using data you collect via Gravity Forms. You can either perform calculations using data from a single form entry, or using data from all entries attached to a specific form.
Calculations for a Single Gravity Forms Entry
Format: [gravitymath scope="entry" id="{entry_id}"]
To perform calculations for a single Gravity Forms entry, you’ll need to use the scope
parameter and set its value to “entry”. You’ll also need to provide the ID of the entry itself. To use Gravity Forms field values in your calculations, use 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 Gravity Form
Format: [gravitymath scope="form" id="{form_id}"]
To perform calculations for all entries in a Gravity Form, you’ll need to use the scope
parameter and set its value to “form”. You’ll also need to provide the ID of the form itself. To use Gravity Forms field values in your calculations, use merge tags.
There are also special modifiers you can add to the Gravity Forms merge tags to fetch different values:
:sum
- The sum of all field values for the form (this is also the default behavior for the form scope).:max
- The highest field value.:min
- The lowest field value.:avg
- The average of all field values.:count
- The number of entries processed.
Calculate the sum of field values:
[gravitymath scope="form" id="9"] {Number:5:sum} [/gravitymath]
Calculate the number of form entries:
[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
You can perform calculations on your Gravity Forms data inside a View created using GravityView. You can do this by placing the [gravitymath]
shortcode inside a Custom Content field or widget.
There are three options when performing calculations inside Views. You can either perform calculations for all entries in a View, only the visible entries, or only the current entry.
Performing Calculations for All Entries in a View
Format: [gravitymath scope="view" id="{view_id}"]
To perform calculations on all entries inside a View, set the scope
parameter to “view” and specify the View ID.
Calculate the sum of field values for all entries in a View:
[gravitymath scope="view" id="27"] {Number:5:sum} [/gravitymath]
When using scope="view"
, please check if the View being referenced in the [gravitymath] shortcode has "Enhanced Security" enabled. When this setting is enabled in the View, the [gravitymath] shortcode will require the use of the secret attribute with the same secret code used by the View. Example: [gravitymath scope="view" id="27" secret="a4e6b12f34"]
Performing Calculations for All Visible Entries in a View
Format: [gravitymath scope="visible"]
Note: This will not work with the DataTables layout.
To perform calculations based on all visible entries in a View, set the scope
parameter equal to “visible”. This works within a GravityView Custom Content Field or Custom Content Widget, as well as when placed on the same page as a [gravityview]
shortcode. The calculation result will change based on which entries are currently visible in the View.
Display the total number of sales:
[gravitymath scope="visible"] {Sales:12:count} [/gravitymath]
Calculate total revenue:
[gravitymath scope="visible"] {Product:3} + {Another Product:4} decimals="2" [/gravitymath]
Performing Calculations for the Current Entry in View
Format: [gravitymath scope="entry"]
To perform calculations using the current entry, set the scope
parameter equal to “entry” and don’t define the id
parameter. (This only works for the Custom Content Field, not the Widget).
Example:
[gravitymath scope="entry"] {Number:5} * 5 [/gravitymath]
Calculating Summaries Using Filters
Using the filter
parameter, you can group Gravity Forms entries by a specific field value and then perform math operations on entries within those groups. The filter
parameter only works for scope="view"
or scope="form"
.
Here’s an example:
[gravitymath scope="view" id="12" filter="filter_1=Yes"]
Here’s a breakdown of all the filtering parameters:
filter_N
- the filter, where N is the ID of the field, entry attribute, or a meta key that you want to filter byop_N
- the operation for a correspondingfilter_N
, default:is
limit
- the number of entries, (default is0
, i.e., process all the entries)
To learn more about calculating summaries using the filter parameter, read How to Display Summaries Using [gravitymath].
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} [/gv_math2] + [gravitymath2 scope="form" id="4"] {Product:2} * {quantity:2} [/gv_math2] [/gravitymath]
Read this article to learn more about nesting [gravitymath]
shortcodes.
All Shortcode Parameters
decimals
- The number of decimals to display. If undefined, displays the number of decimals returned by the math result.format
- Whether or not to format the number. If set toraw
- Display the number, unformatted. Otherwise, format the number using WordPress'number_format_i18n()
function.formula
- Instead of defining the formula inside the shortcode you can define it using theformula
parameter.debug
- Show or hide error messages. Eithertrue
orfalse
.filter
- Used to target a specific field value. Only works withscope="view"
orscope="form"
.default_value
- If a value is not valid, use the default value. Passtrue
to enable, orskip
to skip the invalid value. (Default:skip
).notices
- Display notices to end users if there are warnings or errors associated with the formula. Passtrue
to enable. (Default:false
).gravityview/math/accuracy_message
shortcode available to override default warning notice. (Default: * Results may not be accurate.)gravityview/math/no_results_message
shortcode available to override default Error notice. (Default: ** No Results Currently Available.)gravityview/math/admin_notice
shortcode available to override default Admin notice. (Default: You can only see this message because you are logged in and have permissions.)
Parameters Available When Performing Calculations on Gravity Forms Data
id
- The ID of the form, entry, or View (ifscope
is defined). Default:undefined
.scope
- If not defined, the shortcode performs pure math.form
- Use the sum of all the form values for the specified form ID. Requires anid
parameter.entry
- Use the values of a single entry. Requires theid
parameter if used outside a Custom Content field, otherwise, not needed.visible
- Use the values of only visible entries for the current GravityView View. Must be used inside a Custom Content widget on a View. It doesn't work with DataTables.view
- Use the values of all valid entries for the specified View ID. Requires anid
parameter.
All Supported Math Functions and Constants
Here’s a list of all the mathematical functions and constants supported by [gravitymath]
. You can use these with any scope.
Functions
The [gravitymath]
shortcode supports the following mathematical functions:
abs()
- Returns the absolute value of a number. Learn more.acos()
- Returns the arccosine (in radians) of a number. Learn more.asin()
- Returns the arcsine (in radians) of a number. Learn more.atan()
- Returns the arctangent (in radians) of a number. Learn more.avg( num1, num2, etc )
- Returns the mean of all the items passed to the function. Example:avg( 3, 9, 27 )
returns13
( The sum of the numbers, 39, divided by the item count 3).ceil()
- Returns the smallest integer greater than or equal to a given number. Example:ceil( 10.284742 )
returns11
. Learn more.cos()
- Returns the cosine of a number. Learn more.count()
- Returns the number of items passed to the function. Example:count( 1, 2, 3, 4 )
returns4
. Learn more.deg2rad()
- Returns the number of radians converted from the number in degrees. Learn more.exp()
- Returnsex
, wherex
is the argument, ande
is Euler's constant, the base of the natural logarithms. Learn more.floor()
- Returns the largest integer less than or equal to a given number. Learn more.log( number, e )
- Returns the natural logarithm (base e) of a number. Learn more.max( num1, num2, etc )
- Returns the largest of zero or more numbers. Learn more.min( num1, num2, etc )
- Returns the smallest of zero or more numbers. Learn more.pow( base, exponent )
- Returns the base to the exponent power, that is, base^exponent. Learn more.rad2deg()
- Returns the number of degrees converted from a radian number. Learn more.round( number, precision )
- Returns the rounded value of val to specified precision (number of digits after the decimal point).precision
can also be negative or zero (default). Learn more.sin()
- Returns the sine of a number. Learn more.sqrt()
- Returns the square root of a number. Learn more.sum( num1, num2, etc )
- Returns the total resulting from the addition of the items passed to the function.
Constants
The [gravitymath]
shortcode supports the following mathematical constants:
PI
- π constant (Defaults to 13 decimal places:3.1415926535898
).PI_2
- π constant / 2 (1.5707963267949
).PI_4
- π constant / 4 (0.78539816339745
).E
- e constant (2.718281828459
).SQRT_PI
- Square root of π (1.7724538509055
).SQRT_2
- Square root of 2 (1.4142135623731
).SQRT_3
- Square root of 3 (1.7320508075689
).LN_PI
- The natural logarithm of π (1.1447298858494
).
Note: The number values represented below are defined by PHP. We know the numbers below aren't all limited to 13 decimal places.
Math Function Examples
[gravitymath] ceil( ( 51 * 2 ) + ( 15 / 2 ) ) [/gravitymath]
Will return: 110
because the formula inside the function (( 51 * 2 ) + ( 15 / 2 ))
equals 109.5
. That value is then passed to the ceil()
function, which finds the next highest integer. The next highest integer is 110
.
[gravitymath] round( 42.8 ) [/gravitymath]
Will return 43
because .8
rounds up.
Notes on Shortcode Use
Here are some important things to keep in mind when using the [gravitymath]
shortcode.
General Things to Know
- Decimals require a leading number:
50 + .5
is invalid because the decimal doesn't have a number in front of it. Use50 + 0.5
instead. - If using a Gravity Forms merge tag for a price, make sure to add
:price
to the end of the merge tag. This will convert the currency format (with currency symbol like $) to a number format:- Total fields:
{Total:32}
becomes{Total:32:price}
- Product fields:
{Product Name (Price):28.2}
becomes{Product Name (Price):28:price}
- note that you need to remove the.2
from the end of the field number (28.2
to28
, for example)
- Total fields:
- Nest away! You can nest parenthesis to your heart's delight. An equation like
( 1 + 2 ) + ( 3 / ( 4 * ( 5 + 6 ) ) )
will work just fine. - Extra spacing is not a problem - you can use extra spacing in the formula inside the
[gravitymath]
shortcode tags; line breaks inside the formula parameter aren't allowed. Example of extra spacing that still works:[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 definition, which is has a precision of roughly 14 decimal places. Learn more about floats.
Because of this issue of precision, if the decimal parameter is not defined, the shortcode automatically limits precision to 16 decimal places. This 16 limit can be overridden using the gravityview/math/precision
filter.
// 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; } );