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().
Thank you, threadi! This answer was very helpful, even though I am still clueless to how I can avoid wrong REST API outputs.
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!