WordPress REST API v2 返回所有图像,而不仅仅是来自选定的 Post

WordPress REST API v2 returning all images, not just from selected Post

我正在尝试通过编辑 functions.php 文件向 REST API 添加一些字段。由于我对 WP 没有太多经验,我研究了如何做并想出了以下代码:

add_action( 'rest_api_init', 'add_images_to_JSON' );

function add_images_to_JSON() {
    register_rest_field( 
        'post',
        'images',
        array(
            'get_callback'    => 'get_images_src',
            'update_callback' => null,
            'schema'          => null,
             )
        );
    }

    function get_images_src( $object, $field_name, $request ) {
        $args = array(
            'posts_per_page' => -1,
            'order'          => 'ASC',
            'orderby'        => 'menu_order',
            'post_mime_type' => 'image',
            'post_parent'    => $object->id,
            'post_status'    => null,
            'post_type'      => 'attachment',
            'exclude'        => get_post_thumbnail_id()
        );

        $attachments = get_children( $args );

        $images = [];
        foreach ($attachments as $attc){
            $images[] =  wp_get_attachment_thumb_url( $attc->ID );
        }

       return $images;
    }

问题是,当我按类别获得 post 的列表时,这将返回所有 post 中的所有图像,而不仅仅是与其相关的图像。我怎样才能让每个 post returns 只有它的相关图像?

试试这个:

function get_images_src( $object, $field_name, $request ) {
     $images = [];
     $post_images = get_attached_media('image', $object->ID);
     foreach($post_images as $image) { 
          $images[] = wp_get_attachment_image_src($image->ID,'full');
     }
     return $images;
}