3

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.

0

1 Answer 1

4

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.

3
  • Great, it's working. Now need to see how to get an object per item containing the original source url and the dimensions. Commented Nov 7, 2017 at 15:07
  • 1
    return $gallery; only gives me a list of thumbnail images. How can I get the full image url along with the width and height? Commented Nov 7, 2017 at 15:10
  • 1
    @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. Commented Nov 7, 2017 at 15:19

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.