• Hello,

    I am using REST API to display the metadata of media items from my library.

    There is an unusual occurance that troubles me:

    Whenever a media item has no Caption text but a Description text, the rest API displays the Description text also in the Caption field!

    I have some media like that on this REST Feed Page, for instance:

    https://import.xm-agentur.de/wp-json/wp/v2/media/379804

    Even though there is no caption when I open the image in the library, the description’s content is displayed in the caption field.

    This occurs on several of my WP installations and I would like to find out how I can bypass it.

    All help is appreciated.

    Felix from XM

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator threadi

    (@threadi)

    What you’re seeing is completely normal behavior from WordPress regarding excerpts.

    In WordPress, a caption is handled exactly like post excerpts. If one is specified, it appears in the post_excerpt field of the attachment record. If none is specified, the normal text (in this case, the description, since it is equivalent to post_content) is used and, if necessary, shortened and cleaned up using the usual methods.

    If you want to prevent this, you would need to deactivate this filter here:

    add_filter( 'get_the_excerpt', 'wp_trim_excerpt', 10, 2 );

    You can do this, for example, with this line:

    remove_filter( 'get_the_excerpt', 'wp_trim_excerpt', 10, 2 );

    However, you will then no longer have excerpts in the frontend or for any posts and other post types. You may therefore need to remove the filter only for REST API requests. You can determine this using wp_is_rest_endpoint().

    Thread Starter xmagentur

    (@xmagentur)

    Thank you, threadi! This answer was very helpful, even though I am still clueless to how I can avoid wrong REST API outputs.

    Thread Starter xmagentur

    (@xmagentur)

    Thank you for your help. It is bad that you cannot undo the excerpt-filter for attachments only. We have now gone for an approach like this:

    // REST-API für Medien anpassen, Untertitel (Caption)
    add_filter('rest_prepare_attachment', function ($response, $post, $request) {

    // Nur Media-Endpoints (inkl. Unterrouten)
    if (strpos($request->get_route(), '/wp/v2/media') !== 0) {
    return $response;
    }

    // Roher Untertitel (Caption)
    $response->data['caption']['raw'] = $post->post_excerpt;

    return $response;
    }, 10, 3);

    With our other (import-) plugin we have then preferred caption.raw from the rest api output.
    Thanks for contributing!

Viewing 3 replies - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.