Add a Formatted Date to the WordPress REST API JSON Response

By default, the WordPress REST API returns the post date in date time format. This is not ideal when we want to display a formatted date using a Javascript framework like Vue or React. We could reach for the popular Moment.js library to parse our date, but why add the unnecessary bloat to our Javascript, when we can just add the formatted date directly to the JSON response.

Fortunately, the WordPress REST API provides us with the register_rest_field function, which we can use to add custom properties to the JSON response. Let’s add a formatted date to the post object response by hooking into the rest_api_init function and registering our new field.

/**
 * Add a Formatted Date to the WordPress REST API JSON Post Object
 *
 * https://adambalee.com/?p=1547
 */
add_action('rest_api_init', function() {
    register_rest_field(
        array('post'),
        'formatted_date',
        array(
            'get_callback'    => function() {
                return get_the_date();
            },
            'update_callback' => null,
            'schema'          => null,
        )
    );
});

Adding the code above to functions.php will return the following result in the JSON post object returned by the WordPress REST API.

{
    "formatted_date": "December 24, 2019"
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you in need of a freelance web developer?

Hire me