[wp-trac] [WordPress Trac] #65251: Response from media library API query includes an empty array rather than an empty object
WordPress Trac
noreply at wordpress.org
Fri May 15 14:29:06 UTC 2026
#65251: Response from media library API query includes an empty array rather than
an empty object
------------------------------+-----------------------------
Reporter: frankieandshadow | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: REST API | Version: 6.9.4
Severity: normal | Keywords:
Focuses: |
------------------------------+-----------------------------
In the response to a media library query over the REST API, I am seeing
that $wpimage->media_details->sizes is an empty array when there are no
sizes, rather than an empty object (as a non-empty instance is an object).
This discrepancy is inconsistent and breaks my recipient code. It's
characteristic of json_encode being used on a keyed PHP array, when it
can't tell the difference between keys and numeric indexes when empty.
I asked claude.ai to locate the bug to make it easy for you to fix. It
agreed with my diagnosis and said:
File: wp-includes/rest-api/endpoints/class-wp-rest-attachments-
controller.php
Method: prepare_item_for_response()
The bug: when wp_get_attachment_metadata() returns metadata with an empty
sizes array (image too small for sub-sizes), the method populates
`$data['media_details']` from that metadata but never explicitly sets
`$data['media_details']['sizes']` to new stdClass. The `else {
$data['media_details']['sizes'] = new stdClass; }` branch is only reached
when $metadata itself is empty/falsy. The result is that sizes is either
absent or an empty PHP array `[]` in the JSON output, rather than `{}`.
Prior art: reference Trac #51393, which addressed a related inconsistency
but didn't fix this code path.
Your fix suggestion: initialise `$data['media_details']['sizes']` to `new
stdClass` (or cast with (object)) before the loop that populates it, so
the empty case is covered unconditionally.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/65251>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list