I’ve implemented a neat feature on the front page of my other website: it calculates how long Julia and I have been married. Rather than this being one of those items I will certainly forget to update in the future, it uses a shortcode in the regular page text to calculate this value.
The WordPress function current_time() returns the value of “right now”, and the rest is PHP maths under the hood. Here’s how I did it:
I’m specifying both times as string values. The first one is my known wedding date (Vegas time), and the second is returned by WordPress. The mysql parameter returns the date in the same format I’m supplying above it. The PHP function strtotime will then convert these values into a date object so they can be calculated via subtraction.
The result of that gives us seconds, which I’m converting via minutes, hours and days into years. It’s such a crummy value because of our leap year calculation in the Gregorian calendar. My year value will be a float, so I’m rounding it down to get a whole number.
The last block sets up my code as a shortcode. I’ve explained how to do this in detail in a previous article.