If I have fields for birth date and death date, how do I dynamically display the age of a person? If there is a value specified as the death date, I want to dynamically display: "Deceased" as the life status as well as the age at death. If death date field is blank, I want to dynamically display: "Alive" as the status and the current age of the person.
Hi,
Thank you for contacting us and I'd be happy to assist.
To display, 'Alive' or 'Deceased', you can simply use conditional block, that checks whether the 'death date' field value is empty or not.
( ref: https://toolset.com/course-lesson/using-toolset-conditional-block/ )
For the 'Age' value calculation, you'll need the custom shortcode, that can calculate the age from the 'year' values coming from the born and death fields. And in case the value of death is not set, use the current year.
For example:
add_shortcode('get_age', 'get_age_func');
function get_age_func($atts) {
$data = shortcode_atts( array(
'birth-field' => '',
'death-field' => ''
), $atts );
$birth_year = types_render_field( $data['birth-field'], array( "format" => "Y" ) );
$death_year = types_render_field( $data['death-field'], array( "format" => "Y" ) );
if (empty($death_year)) {
$death_year = date("Y");
}
if (!empty($birth_year)) {
$age = $death_year - $birth_year;
return $age;
}
}
The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.
And to show the Age number/value, you can load this shortcode like this:
[get_age birth-field='born-date-slug' death-field='death-date-slug']
Note: You'll replace 'born-date-slug' and 'death-date-slug' with your actual field slugs.
I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar