2

I just added a gallery to my post and want to access its images through the rest API. In the rest API, I can access the attachments of a post. But those attachments have other images, not in the gallery. For example, I just removed an image from the gallery and it's still there in the attachments.

2

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.

  • Great, it's working. Now need to see how to get an object per item containing the original source url and the dimensions. – THpubs Nov 7 '17 at 15:07
  • return $gallery; only gives me a list of thumbnail images. How can I get the full image url along with the width and height? – THpubs Nov 7 '17 at 15:10
  • @THpubs Take a look at example data output for what information get_post_gallery() is providing you. Everything else you have to get, build yourself. – Nicolai Nov 7 '17 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.