This step-by-step tutorial on how to display an automatically updating years of experience badge on your WordPress site.
Create a PHP Function
The first step is to write a PHP function that calculates the number of years that have passed since a given date. For the purposes of this tutorial, we’ll use August 1, 2010, as the start date.
Add the following PHP function to your functions.php
file in your WordPress theme, or use a plugin like Code Snippets to insert the code:
function years_since_2010() {
$today = new DateTime();
$start_date = new DateTime('2010-08-01');
$diff = $today->diff($start_date);
return $diff->y; // returns the years difference
}
add_filter( 'bricks/code/echo_function_names', function() {
return [
'years_since_2010',
];
} );
Understanding the code
- We initialize two
DateTime
objects—$today
represents the current date, while$start_date
is set to August 1, 2010. - By calling the
diff
method on the$today
object and passing the$start_date
object, we calculate the time difference. - Finally,
$diff->y
extracts the year portion from the difference, which we return from theyears_since_2010
function.
Implementing the Function in Your Design
Once you have added the function, proceed to your page design, and within your editor (for this tutorial, we’ll be using the Bricks Editor), select the element where you want to display the years of experience.
Insert
{echo:years_since_2010}
in the relevant field to output the result of our years_since_2010
function.
Whitelisting Your Function
For the dynamically generated badge to work properly, we’ll need to whitelist our function in Bricks. This is a security measure that allows the function to be called from within the Bricks template.
Add this PHP snippet to your functions.php
file or your code snippet tool:
add_filter( 'bricks/code/echo_function_names', function() {
return [
'years_since_2010',
];
} );
After completing the steps above, check your website’s front-end display. The element you edited should now be showing the number of years since August 1, 2010. As time progresses, this badge will automatically update each year to reflect the correct number of years of experience.