July 13, 2022

Dynamically calculating a date difference in WordPress

I don't usually post this kind of content here, but I thought this might be helpful to others. I build a lot of small business websites and often times it's nice to mention how many years they've been in business. That number will obviously change every year, and no one wants to log in to a website every year just to change a number – so why not do it with JavaScript now that WordPress supports it natively with the Gutenberg editor?

All you have to do is create a Custom HTML block, where you can add your text and this code where the year needs to go (in this case for a business founded in 1984):

<script>document.write(new Date().getFullYear() - 1984)</script>

Here's what it looks like in practice, wrapped in a <blockquote> element with a bit of text:

<blockquote class="wp-block-quote"><p>Founded <script>document.write(new Date().getFullYear() - 1984)</script> years ago</p></blockquote>

Founded years ago

And there you have it – that number of years will automatically increase by 1 on January 1st!

Categorized in: 
Tagged With: 
« Return to blog index