Automatically Calculate Number Of Years Output In Bricks Builder

A useful way to automatically output number of years since a start date in Bricks Builder.

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' );
Snippet added to WPCodebox

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.

Adding to Gutenberg paragraph
Adding to Bricks Rich Text Editor

NOTE: You won’t see the output in the builder or editor view – only on the front end.

Output shown on 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.

Leave the first comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Amanda Lucas

Amanda Lucas runs a web design agency in Ireland called Itchy Fingers Design. She enjoys creating websites that help support business goals and growth and sharing her knowledge.