Make WordPress Core

Opened 2 years ago

#55672 new enhancement

Media endpoint allows multiple media types on request, but only returns image in response

Reported by: grezvany13nl's profile grezvany13nl Owned by:
Milestone: Awaiting Review Priority: normal
Severity: minor Version: 6.0
Component: REST API Keywords:
Focuses: rest-api Cc:


The REST API for attachments (/wp-json/wp/v2/media/) allows to search for specific types based on get_allowed_mime_types(), giving a full range of types to be used.
However the response of the same endpoint only returns 'image' or 'file' (aka everything else).

This causes issues when requesting multiple types, since it won't be possible to differentiate them by type anymore (mime type is still correct). It's an issue I found while building a custom editor (Gutenberg) block which can handle multiple types (image, video, audio and pdf)

Code which causes the issue:

if ( in_array( 'media_type', $fields, true ) ) {
   $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';

At the moment I use a workaround which modifies the REST response.

function get_real_media_type($post_id)
    switch (true) {
        case wp_attachment_is('image', $post_id):
            return 'image';
        case wp_attachment_is('video', $post_id):
            return 'video';
        case wp_attachment_is('audio', $post_id):
            return 'audio';
        case wp_attachment_is('pdf', $post_id):
            return 'pdf';
        // add more types?

        // when no predefined type, return 'file'
            return 'file';

add_filter('rest_prepare_attachment', function ($response, $post, $request) {
    if (
        && property_exists($response, 'data')
        && array_key_exists('media_type', $response->data)
    ) {
        $response->data['media_type'] = get_real_media_type($response->data['id']);

    return $response;
}, 10, 3);

Extend the response code for media files to include more different media types, instead of only 'image' and 'file'.
This shouldn't cause any backwards compatibility issues, since 'image' will still work and 'file' will still be there in case it's a non-standard type.

Change History (0)

Note: See TracTickets for help on using tickets.