Search code examples
phpwordpressrestwordpress-rest-api

How can I add embed attachments in WordPress REST response?


I use WP REST API 2.0 for REST API support. How can I get attachments in _embedded property of wordpress response? I passed _embed parameter but I did not get wp:attachment object. Fully url: /wp-json/wp/v2/posts?_embed

enter image description here

I expect response, like this:

enter image description here


Solution

  • You can add specific action for that with register_rest_field function.

    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));});
    

    Now in your func_to_get_meta_data you have to call get_attached_media for example for all medias.

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

    In this example i get all images attached to a post or custom post.