UPDATED: 30th November 2023
A very useful way to add an automatically calculated number of years output. For example, a client’s ‘About’ page may refer to how many years they’ve been in business. This is definitely not something you want to edit each year.
This article will show how to automate the output.
First, you’ll need to add the following code snippet to whatever you use for custom code (I use WPCodebox) :
function years_since_date_shortcode($atts) {
$atts = shortcode_atts(
array(
'date' => '', // Add your date parameter here
),
$atts,
'years_since_date'
);
$given_date = strtotime($atts['date']);
$current_date = time();
$years_since = date('Y', $current_date) - date('Y', $given_date);
return $years_since;
}
add_shortcode('years_since_date', 'years_since_date_shortcode');
Simply change the 'startdate'
to the required date. This code uses PHP to calculate the difference between the current year and the start date, then outputs the result.
Once you’ve added the code snippet, output the result where you want to using the shortcode :
[years_since_date date="your_date_here"]
Use the date format: DD/MM/YYYY
Simply type the shortcode into your content. You will see the number of years since the start date displayed on your website.
NOTE: You won’t see the output in the builder or editor view – only on the front end.
This is a great way to dynamically show number of years without having to edit each year. A very simple but useful method.