Add the following code to register a custom shortcode ‘age’:
/** * Calculate age (in years) from date field * specified as shortcode attribute 'slug' */ add_shortcode( 'age', function( $atts = [], $content = null ){ // provide defaults $atts = shortcode_atts( array( 'slug' => null ), $atts ); $age = ''; if ( isset( $atts['slug'] ) ) { global $post; $timestamp = get_post_meta( $post->ID, 'wpcf-' . $atts['slug'], true ); $date = DateTime::createFromFormat( "U", $timestamp ); $now = new DateTime(); $diff = $now->diff( $date ); $age = $diff->y; } return $age; });
You would use it like so to output the age in years calculated from a Types date field with a slug specified by the slug shortcode attribute:
Age: [age slug='date-of-birth']
Let us know if this snippet is not working for you:
This snippet doesn’t work