Skip to content

Co-Authors Plus WordPress JSON REST API

I was trying to figure out if someone already wrote an REST API endpoint for WordPress Co-Authors plugin. There is wp-api-co-author-plus-endpoints, but it seems that it is focused on guest authors. For my project I needed to include information about co-author users. It turns out it’s very simple to extend existing REST API endpoints.

Here’s a full snippet:

<?php

if ( function_exists('get_coauthors') ) {
    add_action( 'rest_api_init', 'custom_register_coauthors' );
    function custom_register_coauthors() {
        register_rest_field( 'post',
            'coauthors',
            array(
                'get_callback'    => 'custom_get_coauthors',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    }

    function custom_get_coauthors( $object, $field_name, $request ) {
        $coauthors = get_coauthors($object['id']);

        $authors = array();
        foreach ($coauthors as $author) {
            $authors[] = array(
                'display_name' => $author->display_name,
                'user_nicename' => $author->user_nicename
            );
        };

        return $authors;
    }
}

This allows you to query http://wordpress.domain.com/wp-json/wp/v2/posts/213540 and get coauthors key back in response.