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) :
<?php
function yearssince_shortcode($atts) {
$atts = shortcode_atts(array(
'startdate' => '1/08/2014',
),
$atts
);
$startdate = new DateTime($atts['startdate']);
$today = new DateTime(date('d/m/Y'));
$datediff = $today->diff($startdate);
$yeardiff = $datediff->y;
return $yeardiff;
}
add_shortcode( 'yearssince', 'yearssince_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 :
[yearssince]
Simply type the shortcode into the Gutenberg paragraph element or add it to the Rich Text element in Bricks Builder. 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.