WordPress Shortcode to Display Post’s Last Modified Date

by | April 30, 2023 | PHP, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

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.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

17 − four =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest