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