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.
1 Answer
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– THpubs2017-11-07 15:07:12 +00:00Commented 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?THpubs– THpubs2017-11-07 15:10:39 +00:00Commented 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.Nicolai Grossherr– Nicolai Grossherr2017-11-07 15:19:54 +00:00Commented Nov 7, 2017 at 15:19