age-shortcode-php

Render an Age (from DOB) in WordPress with Shortcode

On one of the sites we worked on last year we would often note the age of a person (or years since an event) in the article body. Since much of the information we share is timeless in nature it makes sense to always have a dynamic (always up-to-date) age calculation. The WordPress shortcode function on this page will show you how to include the current age of a person (or years since a any event).

The Result

To display the current age of Jennifer Lawrence we would use the shortcode of [age dob="19900805"] (see below for other date options). The result: 26.

The Shortcode Function

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Date Formats

PHP’s strtotime() function recognises only certain patterns and it’s easy to confuse date formats because of the backwards way the USA represents the date. The American m/d/y is assumed with slashes; however, if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential ambiguity, it’s best to use ISO 8601 (YYYY-MM-DD). In my example above I’ve used the 6 figure time group of YYYYMMDD (without any separator). An English representation is okay as well; for example, [age dob="25 December 2005"] will work.

Download the Code

Download the shortcode function here .

Shortt URL for this post:

Leave a Reply

Your email address will not be published. Required fields are marked *