I have been building a member-based website recently for a client and needed to display the age on the profile page. I was using Advanced Custom Fields to build the profiles and used the datepicker field to set the date.
To calculate this, use the snippet below to achieve what you need.
<?php
if(get_field('date_of_birth')) {
$date = get_field('date_of_birth');
$birthday = new DateTime($date);
$interval = $birthday->diff(new DateTime);
?>
<p>Age: <strong><?php echo $interval->y; ?></strong></p>
<?php } ?>
Would there be a way to display the Age in weeks instead of years? I have a client who raises puppies and wants to show the age of each puppy in weeks. Thanks!
You could get the value of days from the dates difference and then divide by 7 to get the number of weeks, using some PHP calculations.
if(get_field('date_of_birth')) {
$date = get_field('date_of_birth');
$birthday = new DateTime($date);
$interval = $birthday->diff(new DateTime);
$days = $interval->days;
$weeks = (int) ($days / 7);
And then in the template, call it like this:
echo $weeks;
That should convert the date into weeks, not tested but should do the job.
P
Hi Phil,
Im using ACF and want a field to display Age by entering the Date of birth. Where would i paste this PHP code? Into a theme file or somewhere in ACF?
thanks!
Hi Jim,
Assuming you have the ACF field set up and named like the example, you would add this snippet into the PHP template file where you wish to show the age.
Hope this helps.
Phil