By Stephen Walker
Share
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.
function format_date_in_ap_style($date_string, $d = '', $post = null) {
$post = get_post($post);
if (!$post) {
return $date_string;
}
// Get timestamp based on current filter
if ('get_the_modified_date' === current_filter()) {
$timestamp = strtotime($post->post_modified);
} else {
$timestamp = strtotime($post->post_date);
}
// Get the difference in days
$days_difference = (current_time('timestamp') - $timestamp) / DAY_IN_SECONDS;
if ($days_difference <= 180) {
// Get human-readable time difference
return human_time_diff($timestamp, current_time('timestamp')) . ' ago';
} else {
// Get the date in AP style
$ap_month_format = array(
'January' => 'Jan.', 'February' => 'Feb.', 'March' => 'March', 'April' => 'April',
'May' => 'May', 'June' => 'June', 'July' => 'July', 'August' => 'Aug.',
'September' => 'Sept.', 'October' => 'Oct.', 'November' => 'Nov.', 'December' => 'Dec.'
);
$month_name = $ap_month_format[date("F", $timestamp)];
$day = date("j", $timestamp);
$year = date("Y", $timestamp);
return $month_name . ' ' . $day . ', ' . $year;
}
}
add_filter('get_the_date', 'format_date_in_ap_style', 10, 3);
add_filter('get_the_modified_date', 'format_date_in_ap_style', 10, 3);
Originally published on Sept. 8, 2023