By Stephen Walker

Share

After a few iterations to get the right combo, another win for ChatGPT. The prompt:

Create a WordPress shortcode that returns the published date or modified date of a post in an Associated Press style date format with months longer than five letters abbreviated.

The following code allows you to use the shortcode ap_date to show the published date in AP style format or ap_date type="modified" to show the modified date in AP style format.

To create a WordPress shortcode that returns the published date or modified date of a post in Associated Press (AP) style date format, you need to add the following code to your theme’s functions.php file or your code snippet manager:

<?php
function ap_style_date($atts) {
    $atts = shortcode_atts(
        array(
            'type' => 'published',
        ), $atts, 'ap_date'
    );

    global $post;
    $date = '';

    if ($atts['type'] === 'modified') {
        $date = get_the_modified_date('Y-m-d', $post->ID);
    } else {
        $date = get_the_date('Y-m-d', $post->ID);
    }

    $date_obj = new DateTime($date);
    $month = $date_obj->format('F');
    $day = $date_obj->format('j');
    $year = $date_obj->format('Y');

    $months_to_abbreviate = array('January', 'February', 'August', 'September', 'October', 'November', 'December');
    $month_abbreviations = array('Jan.', 'Feb.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.');

    if (in_array($month, $months_to_abbreviate)) {
        $month = str_replace($months_to_abbreviate, $month_abbreviations, $month);
    }

    return $month . ' ' . $day . ', ' . $year;
}

add_shortcode('ap_date', 'ap_style_date');

Originally published on March 16, 2023

Category Dropdown Shortcode
Outdated Content Shortcode

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