如何在 WordPress REST 响应中添加嵌入附件?

How can I add embed attachments in WordPress REST response?

我使用 WP REST API 2.0 来支持 REST API。如何在 wordpress 响应的 _embedded 属性 中获取附件?我传递了 _embed 参数,但没有得到 wp:attachment 对象。完全 url: /wp-json/wp/v2/posts?_embed

我期待回复,例如 this:

您可以使用 register_rest_field 功能为其添加特定操作。

add_action('rest_api_init', function(){register_rest_field('your_post_type', 'field_to_show_in_response', array('get_callback' => 'func_to_get_meta_data', 'update_callback' => null, 'schema' => null));});

现在,在您的 func_to_get_meta_data 中,您必须为所有媒体调用 get_attached_media

function func_to_get_meta_data($obj, $name, $request){return get_attached_media('image', $obj['id']);}

在此示例中,我将所有图像附加到 post 或自定义 post。