These can be dropped into your functions.php to enable various shortcodes.
Sortable Date
This one takes a date string as its input and will display a date that is in the order Year Month Day, which can be used when you need to sort a column of dates numerically, for example.
[sortable_date]01/12/2016[/sortable_date]
Output: 20161201
/** * Converts date into numerically sortable format * e.g. 1 December 2017 * => 20171201 * * @param string $string containing a date string * @return string */ function convert_date_to_sortable( $atts, $content = "" ) { $ukdate = strtotime(str_replace('/', '-', $content)); $sortabledate = date('Ymd',$ukdate); return $sortabledate; } add_shortcode( 'sortable_date', 'convert_date_to_sortable' );
Convert Sortable Date to UK Date
This converts the date from Ymd to d/m/Y
[sortable_date_to_uk]20161201[/sortable_date_to_uk]
Output: 01/12/2016
<?php /** * Converts Ymd date into uk slashed format * e.g. 20171201 * => 01/12/2017 * * @param string $string containing a date string * @return string */ function convert_sortable_date_to_uk( $atts, $content = "" ) { $dashed = $content[6].$content[7].'-'.$content[4].$content[5].'-'.$content[0].$content[1].$content[2].$content[3]; $newformat = date( 'd/m/Y', strtotime( $dashed ) ); return $newformat; } add_shortcode( 'sortable_date_to_uk', 'convert_sortable_date_to_uk' );
Age in Years
This one takes a date string (e.g. a date of birth) as its input and will display the age in years as a number. For example:
[date_to_age]01/12/2016[/date_to_age]
Output: 2
<?php /** * Converts date string into age in years * e.g. 1 December 2016 or 1 Dec 2016 or 01/12/2016 * => 2 * * @param string $string containing a date string * @return string */ function convert_date_string_to_age( $atts, $content = "" ) { $ukdate = strtotime(str_replace('/', '-', $content)); // omit if using U.S. d/m/Y $usdate = date('m/d/Y',$ukdate); $age = date_diff(date_create($usdate), date_create('now'))->y; return $age; } add_shortcode( 'date_to_age', 'convert_date_string_to_age' );