WordPress REST API v2返回所有图像,而不仅仅是返回选定的帖子

问题描述 投票:0回答:1

我正在尝试通过编辑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;
    }

问题是,当我按类别获取帖子列表时,这将返回所有帖子中的所有图像,而不仅仅是与之相关的图像。如何使每个帖子仅返回其相关图像?

wordpress wordpress-rest-api
1个回答
0
投票

尝试一下:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.