How to add years elapsed since?

[ad_1]

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.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer