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