【问题标题】:WordPress REST API v2 returning all images, not just from selected PostWordPress REST API v2 返回所有图像,而不仅仅是来自选定的帖子
【发布时间】:2020-02-26 07:06:57
【问题描述】:

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

    试试这个:

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

    【讨论】:

    • 这几乎奏效了。 wp_get_attachment_image_src 返回了一个数组。我不得不在它后面加上 [0],但它似乎有效。谢谢!
    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多