How to get the attached gallery in the rest API?

To my knowledge this can’t be done out of the box. So you could make use of what get_post_galleries() or get_post_gallery(), the latter is just making use of the former, are doing by adding an endpoint.

A minimal example could look like shown below.

function rest_get_post_gallery( $data ) {
    //set FALSE for data output
    $gallery = get_post_gallery( $data[ 'post_id' ], FALSE );

    if ( empty( $gallery ) ) {
        return NULL;
    }

    //comma separated list of ids
    return $gallery[ 'ids' ];
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'gallery_plugin/v1', '/post/(?P<post_id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'rest_get_post_gallery',
    ) );
} );

The following should give you a result now.

http://example.com/wp-json/gallery_plugin/v1/post/<post_id>

I based this on the article Adding Custom Endpoints | REST API Handbook, so for further information take a look at it.

Leave a Comment