By Stephen Walker

Share

WordPress has a great function built-in to express the date posted in a more readable format. This shortcode will let you output either the published date or the updated date in this format. Add the code to your functions.php file or code manager. The shortcode is either [date_human_readable] for the published date or [date_human_readable type="updated"]for the date updated.

function date_human_readable_shortcode($atts) {
    // Extract attributes
    $attributes = shortcode_atts(
        array(
            'type' => 'published',  // Default type is published date
        ), 
        $atts
    );

    $post_date = get_the_date('Y-m-d H:i:s');
    $post_modified_date = get_the_modified_date('Y-m-d H:i:s');
    
    // Determine which date to use and the appropriate prefix based on the 'type' attribute
    if ($attributes['type'] === 'updated') {
        $date_to_use = $post_modified_date;
        $prefix = 'Updated';
    } else {
        $date_to_use = $post_date;
        $prefix = 'Published';
    }

    // Get human-readable time difference
    $human_time_diff = human_time_diff(strtotime($date_to_use), current_time('timestamp'));

    return $prefix . ' ' . $human_time_diff . ' ago';
}
add_shortcode('date_human_readable', 'date_human_readable_shortcode');

Originally published on Sept. 8, 2023

Show Post Status
Replace Date Format

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

RELATED Snippets

  • ChatGPT, PHP

    I prefer to have my dates in human-readable time difference or AP style dates, so this function will replace the default date format and output either the human-readable time difference or if the date difference is more than 180 days, the AP Style date.

  • ChatGPT, PHP

    If you work with numerous non-published posts, it might be helpful to show the status. This shortcode shows the status if the status is currently not “Publish.”

  • ChatGPT, PHP, Shortcode

    I used ChatGPT to generate a shortcode that would indicate whether a business is opened or closed.

  • Advanced Custom Fields (ACF), PHP, Plugins

    Since ACF turns off the WordPress custom fields, this snippet will bring them back. Just add it to your functions.php or your favorite code manager

  • PHP, Shortcode

    I wanted to show the date the article was posted and the date updated if the dates differ. This shortcode will do just that.

  • PHP, Shortcode

    I needed a way to get the first letter of the post title without requiring a custom field. An example of its use can be seen on the First Initial Post Card.