Creating a shortcode for current year in WordPress
Just when I thought I had left WordPress behind, I recently found myself trying to figure out how to dynamically add the year on a copyright notice. There are many ways you can accomplish this. My favorite solution is by using shortcodes. However, I can’t believe that WordPress still doesn’t offer some basic shortcodes out-of-the-box, like the current year! 🤔.
If you do a quick look up on how to do this you may go nuts. There’s a lot of creativity out there 😁.
By the way, I haven’t being a fan of WordPress for a while, but I find no shame in using it. Despite being one of the oldest products in web development it still offers a ton of useful resources. In fact, I recently started using it for powering the backend of a few headless projects where the frontend is React, Astro or something other than WP.
So, here is how I like to do this.
Create the shortcode in functions.php
. It’s recommended to do this in a child theme.
// Register a shortcode for returning current year.
if (!function_exists('current_year_shortcode')) {
function current_year_shortcode() {
return date('Y');
}
}
add_shortcode('current_year', 'current_year_shortcode');
Then, you can use [current_year]
and it should do the magic for you.
First, select the “Shortcode” block.
Next, add your text in this block and make sure to include [current_year]
.
That’s it. Cheers!