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

Human Readable Time
Get your image to fill the space

Leave a Reply

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

RELATED Snippets

  • ChatGPT, PHP, Shortcode

    WordPress has a great function built-in to express the date posted in a more readable format.

  • 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.