Here’s a WordPress shortcode to display a “last modified” date on your website’s posts or pages if and only when the modification date is different than the date the post was published. The idea is to show the last modified date to let readers know your content has changed or been updated since the time of its original publishing. Else, if you have not updated the content, there’s no need to display the last modified date.
PHP Code
Add the following PHP code snippet to your active theme’s functions.php
file.
function last_modified_shortcode() {
$published_date = get_the_date('F j, Y');
$modified_date = get_the_modified_date('F j, Y');
if ($published_date !== $modified_date) {
$output = '<span class="last-modified-date">' . __('Last updated on: ', 'text-domain') . $modified_date . '</span>';
return $output;
}
}
add_shortcode('last-modified', 'last_modified_shortcode');;
This code creates a shortcode function called last_modified_shortcode()
that retrieves the modified date and the published on date of the current post and formats each using the get_the_modified_date()
and get_the_date()
functions respectively. It then checks if the modified date is different than the published on date. If the dates are different, it returns the formatted modification date wrapped in a span with a CSS class of last-modified-date which you could use for styling. Finally, the add_shortcode()
function is used to register the shortcode with the name last-modified.
Using the Shortcode
To use the shortcode, simply add in your content where you’d like the last modified date to display.
0 Comments