This is a great-use case for a snippet. I’ve created one and uploaded it to the Code Snippets Cloud website: https://codesnippets.cloud/snippet/shea/time-since-shortcode
Once you’ve added and activated it, you should be able to use it like so:
This company was founded [time_since date=”January 1st 2003″] ago.
To achieve the result:
This company was founded 20 years ago.
It should also adapt to shorter periods of time as well.
Thanks, that works great.
How do I remove the “years”? So it only outputs 20 and not 20 years ?
I prefer to control the text myself.
In that case, you can use this code instead:
add_shortcode( 'years_since', function ( $atts ) {
$atts = shortcode_atts(
[
'date' => '',
],
$atts,
'years_since'
);
$timestamp = strtotime( $atts['date'] );
$diff = (int) abs( time() - $timestamp );
$years = round( $diff / YEAR_IN_SECONDS );
return $years > 0 ? $years : 1;
} );Works the similar to [date_since], but will always only display the number of years as an integer (with no other text), e.g.
This company was founded [years_since date=”January 1st 2003″] years ago.
