[SOLVED] WordPress REST API Not Returning All Images

Problem

I recently noticed the WordPress REST API was not retrieving all images when using the media endpoint /wp-json/wp/v2/media.

The endpoint would return the expected amount of pages – but many of the pages were incomplete, e.g. less than the expected 100 pages.

Solution

After a bit of testing, I noticed that the missing images were all linked to a post.

And that the posts were always a custom post type.

If I changed the post type to the default “post” – the image would appear in the WP REST API media endpoint.

This led to discovering that by default custom post types do not show in the WP REST API.

Strangely, this also includes images attached to the post.

To solve this you need to customise where the custom post type is registered, and set the 'show_in_rest' parameter to true .

To ensure that images linked to custom post types are returned by the WordPress REST API, follow these steps:

  1. Locate the code or settings responsible for registering the custom post type.
  2. Find the registration arguments and locate the 'show_in_rest' parameter.
  3. Set the 'show_in_rest' parameter to true in order to expose the custom post type and its associated images through the REST API.
  4. Save the changes and test the REST API endpoint to verify that the images are now being returned.

Example Code:

// Custom post type registration
$args = array(
'label' => 'Custom Post Type',
// Other arguments...
'show_in_rest' => true, // Enable REST API
);
register_post_type('custom_post_type', $args);

By following these steps and configuring the 'show_in_rest' parameter to true, you can resolve the issue of the WordPress REST API not returning all images associated with custom post types.

This solution allows you to access the attached images through the REST API media endpoint.