In today’s lesson, we’ll return briefly to WordPress and look at how to create a simple shortcode that displays the current date in a custom format. The format will be defined using the PHP date() function.
PHP Code for the Shortcode
The code for our shortcode is very simple and consists of just a few lines:
add_shortcode("date", function($atts)
{
//Sets
$atts = shortcode_atts(array(
'template' => date('Y-m-d'),
),$atts);
return date($atts['template']);
});Where:
date — the name of our shortcode
shortcode_atts() — a WordPress function that sets default attributes for the shortcode. In our case, if the template parameter is not set, the default format Y-m-d will be used (i.e., year-month-day).
date() — a built-in PHP function for working with dates (specifically, displaying them). The first argument is the format template. You can find detailed information about the available formats in the official PHP documentation.
Place this PHP code inside the functions.php file of your theme.
How to Use the Shortcode
To use the shortcode, simply enter the following test content in the WordPress editor:
Without parameter - [date] Year - [date template="Y"] Year and month - [date template="Y-m"] Year, month and day - [date template="Y-m-d"] Current time - [date template="H:i:s"]
I don’t think this needs much explanation — it should be clear from the examples above. But if you have any questions, feel free to ask in the comments.
On the frontend (on a page or post), where the shortcode result is rendered, you’ll see something like this:
Without parameter — 2019-01-12
Year — 2019
Year and month — 2019-01
Year, month, and day — 2019-01-12
Current time — 14:53:36
Of course, the date and time will vary depending on when the shortcode is rendered.
Where could this shortcode be useful? A good question. Right now, I see one obvious use case — in the site footer, where the year of creation and the current year are usually displayed.
To implement something like that, you can use this code:
2014 - <?php echo do_shortcode('[date template="Y"]'); ?>That’s it — good luck!
