Skip to content

Instantly share code, notes, and snippets.

@rafaehlers
Last active May 21, 2018 20:06
Show Gist options
  • Save rafaehlers/95f1661593b8ecfa92002137551f3ea4 to your computer and use it in GitHub Desktop.
Save rafaehlers/95f1661593b8ecfa92002137551f3ea4 to your computer and use it in GitHub Desktop.
Calculate a person's age based on a date field
<?php
add_shortcode( 'gv_age', 'gv_calculate_age' );
/**
* Calculate age in years based on entry data
*
* Usage inside a Custom Content field (Replace "2" with the ID of the date field):
*
* <code>
* [gv_age entry_id="{entry_id}" field_id="2" /]
* </code>
*
* The output will be formatted as the number of years by default. To change the output, define a custom `format`
*
* <code>
* [gv_age entry_id="{entry_id}" field_id="2" format="d" /]
* </code>
*
* This will now output the number of days since the date entered in the field.
*
* @see https://php.net/manual/en/dateinterval.format.php For options on how to format the date difference
*
* Will show error messages by default. Add `hide_errors="1"` to the shortcode to prevent errors from being output.
*
* @param $atts
*
* @return string
*/
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')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment