Calculating a person's age based on a date field

Ever wanted to calculate someone else's age based on a date field? That's possible using the [gv_age] shortcode.

Shortcode Parameters

The [gv_age] shortcode requires two parameters to calculate age.

  • entry_id - The ID of the entry for the age calculation. Can use the {entry_id} Merge Tag or a numeric entry ID.
  • field_id - The ID of the date field where date of birth is stored.

Example

This shortcode will calculate the ages for all entries. Date of birth is stored in a date field with an ID of 44:

[gv_age entry_id="{entry_id}" field_id="44" /]

Adding the [gv_age] shortcode to a Custom Content field:

Replace with your date field ID for age calculation shortcode

The output:

Table showing names, birth dates, and custom ages calculated: Amy 20, Randall 34, Chris 25

Now that we have the age displayed, we can enter a label for the Custom Content field:

GravityView setup to calculate age from a date field with custom label optionAnd voilá:

Table with names, birth dates, and ages: Amy, Randall, Chris; ages: 20, 34, 25

You'll need this code to enable the [gv_age] shortcode:

add_shortcode( 'gv_age', 'gv_calculate_age' );

function gv_calculate_age( $atts ) {

	$defaults = array(
		'field_id'    => '',
		'entry_id'    => '',
		'format'      => '%y',
		'hide_errors' => ''
	);

	$atts = shortcode_atts( $defaults, $atts, 'gv_age' );

	$entry = GFAPI::get_entry( $atts['entry_id'] );

	if ( ! $entry || is_wp_error( $entry ) ) {
		return empty( $atts['hide_errors'] ) ? 'Error: Entry not found' : '';
	}

	if ( empty( $entry[ $atts['field_id'] ] ) ) {
		return empty( $atts['hide_errors'] ) ? 'Error: Field value not specified.' : '';
	}

	$from = new DateTime( $entry[ $atts['field_id'] ] ); // Birth date
	$to   = new DateTime( 'now' );
	$interval = $from->diff( $to );

	return $interval->format( $atts['format'] ); // Default format is years ('%y')
}

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