Making calculations using the custom content field

Using the GravityMath plugin

Let's say you want to add the values from two fields: field "Number One" with an ID of 15 and "Number Two" with an ID of 37. You would just need to insert the Merge Tags of the fields and add them together inside the [gv_math] shortcode. Here's the code you would use:

[gv_math scope="entry"] {Number One:15} + {Number Two:37} [/gv_math]

Learn more about using the [gv_math] shortcode

Using custom code

Is it possible to sum up entries' fields and display the total number using a Custom Content field, without the Math by GravityView plugin? Yes, it is possible using the  gravityview/fields/custom/content_before hook!

To make sure you are addressing the correct custom content field, add a placeholder to the custom content field. For example, add %CALC%.

Then, to enable this logic, you would need to adapt and paste the following code into your website:

/** Modify the content returned from the Custom Content field */
add_filter( 'gravityview/fields/custom/content_before', 'my_gv_custom_content_before', 10, 2 );

/**
 * Replaces the %CALC% placeholder by the result of a calc operation between entries' fields
 *
 * @param  string $content Custom Content field content
 * @param  \GV\Template_Context $context
 * @return string
 */
function my_gv_custom_content_before( $content, $context = null ) {

	// this is the tag used inside the Custom Content Field
	$tag = '%CALC%';

	// Is the placeholder tag in the Custom Content field? If not, return original value.
	if( false === strpos( $content, $tag ) ) {
		return $content;
	}

	$replace = '';
	
	// If the fields used for the calculation are set, replace the tag with the calculation.
	if( isset( $context->entry['15'] ) && isset( $context->entry['37'] ) ) {
		$replace = $context->entry['15'] +  $context->entry['37'];
	}

	return str_replace( $tag, $replace, $content );
}

Read here how to add these code samples to your website: Where to put code samples.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us