Click here to Skip to main content
15,065,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to display the age in years months and days in Wordpress post given the date of birth in the post. Suppose my date of birth is 14-Sep-1984, so as of today my age is 36 years 7 months 28 days. I tried the following code, but it only displays the years.

What I have tried:

function get_age_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(

), $atts ) );

$date = new DateTime($content);
$now = new DateTime();
$interval = $now->diff($date);
return (' Your age : %d years, %d month, %d days', $interval->y, $interval->m, $interval->d);
}
add_shortcode( 'get_age', 'get_age_shortcode' );
add_filter('widget_text', 'do_shortcode');
Posted
Updated 17-May-21 21:40pm

1 solution

The diff function returns a PHP: DateInterval - Manual[^]. Use the format method to display the values correctly.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900