Get Attached Media For A Certain Post With REST API

UPDATED 03/09/2017: According to the API documentation, we can now use endpoint "wp-json/wp/v2/media?parent=POST_ID" to get the attachments to a certain post without an extra filter. For example:

When trying to get attached media for a certain post in WordPress with JSON REST API, I thought it would be something like:


But it didn’t work. So I turned to to find the solution.

The documentation of retrieve posts and get attachments are not clear enough to show that I may or may not do so with REST API. Luckily I found the following paragraph in the Comparison section: API embeds all attachments in the post. WP API does not currently dothis. Attachments belonging to the post can still be queried via/media?filter[post_parent]=<id>.

I tried it right away but to my surprise, it didn’t work either.

After more googling I saw people posted couple of issues on the GitHub repo of REST API, which reported the same problem as mine.

I got an email this morning from a passionate AngularJS and WordPress learner, Stuart, who generously shared his finding to fix this issue. It turned out couple days after my googling, one of the contributors to REST API, Daniel closed several related issues with the solution: We need to add an extra filter as below to make the media query work.

add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'post_parent';
    return $query_vars;

To be honest I feel this approach is a bit of redundant. The “post_parent” should be a standard query var rather than one we need to hook to enable. But considering to REST API is still a young project and we’re lucky to have so many great developers in WordPress community to get involved, I supposed there must be some reasons to do so.

Now you can go try and see if it works for you. In the following posts of my Building themes with AngularJS and JSON REST API series, I’ll be showing how to build a slider with Angular Slick in your WordPress post. So stay tuned!

Share the post:Tweet about this on Twitter
Share on Facebook
0Share on LinkedIn


Submit a comment

Submit a comment

Your email address will not be published. Required fields are marked *