WP Rest API:最新帖子的详细信息,包括一个请求中的特色媒体网址?


15

我正在使用wp-rest api来获取帖子信息。我还使用wp rest api过滤器项过滤字段并汇总结果:

当我调用http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media它时,返回的结果如下:

[

    {
        "id": 407,
        "title": {
            "rendered": "Title 1"
        },
        "featured_media": 399
    },
    {
        "id": 403,
        "title": {
            "rendered": "Title 2"
        },
        "featured_media": 401
    }

]

问题是如何使用此ID生成特色媒体网址?默认情况下,调用会http://example.com/wp-json/wp/v2/media/401返回一个新的json,其中包含有关不同大小的源图片网址的所有详细信息:

{

    "id": 401,
    "date": "2016-06-03T17:29:09",
    "date_gmt": "2016-06-03T17:29:09",
    "guid": {
        "rendered": "http://example.com/wp-content/uploads/my-image-name.png"
    },
    "modified": "2016-06-03T17:29:09",
    "modified_gmt": "2016-06-03T17:29:09",
    "slug": "my-image-name",
    "type": "attachment",
    "link": "http://example.com/my-post-url",
    "title": {
        "rendered": "my-image-name"
    },
    "author": 1,
    "comment_status": "open",
    "ping_status": "closed",
    "alt_text": "",
    "caption": "",
    "description": "",
    "media_type": "image",
    "mime_type": "image/png",
    "media_details": {
        "width": 550,
        "height": 250,
        "file": "my-image-name.png",
        "sizes": {
            "thumbnail": {
                "file": "my-image-name-150x150.png",
                "width": 150,
                "height": 150,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-150x150.png"
            },
            "medium": {
                "file": "my-image-name-300x136.png",
                "width": 300,
                "height": 136,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-300x136.png"
            },
            "one-paze-port-thumb": {
                "file": "my-image-name-363x250.png",
                "width": 363,
                "height": 250,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-363x250.png"
            },
            "one-paze-blog-thumb": {
                "file": "my-image-name-270x127.png",
                "width": 270,
                "height": 127,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-270x127.png"
            },
            "one-paze-team-thumb": {
                "file": "my-image-name-175x175.png",
                "width": 175,
                "height": 175,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-175x175.png"
            },
            "one-paze-testimonial-thumb": {
                "file": "my-image-name-79x79.png",
                "width": 79,
                "height": 79,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-79x79.png"
            },
            "one-paze-blog-medium-image": {
                "file": "my-image-name-380x250.png",
                "width": 380,
                "height": 250,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name-380x250.png"
            },
            "full": {
                "file": "my-image-name.png",
                "width": 550,
                "height": 250,
                "mime_type": "image/png",
                "source_url": "http://example.com/wp-content/uploads/my-image-name.png"
            }
        },
        "image_meta": {
            "aperture": "0",
            "credit": "",
            "camera": "",
            "caption": "",
            "created_timestamp": "0",
            "copyright": "",
            "focal_length": "0",
            "iso": "0",
            "shutter_speed": "0",
            "title": "",
            "orientation": "0",
            "keywords": [ ]
        }
    },
    "post": 284,
    "source_url": "http://example.com/wp-content/uploads/my-image-name.png",
    "_links": {
        "self": [
            {
                "href": "http://example.com/wp-json/wp/v2/media/401"
            }
        ],
        "collection": [
            {
                "href": "http://example.com/wp-json/wp/v2/media"
            }
        ],
        "about": [
            {
                "href": "http://example.com/wp-json/wp/v2/types/attachment"
            }
        ],
        "author": [
            {
                "embeddable": true,
                "href": "http://example.com/wp-json/wp/v2/users/1"
            }
        ],
        "replies": [
            {
                "embeddable": true,
                "href": "http://example.com/wp-json/wp/v2/comments?post=401"
            }
        ]
    }

}

但是,当我想获取帖子列表及其缩略图时,请考虑这种情况。一次,我应该为每个媒体ID http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media调用http://example.com/wp-json/wp/v2/media/id10次​​,然后解析结果并获得媒体缩略图的最终URL。因此,它需要11个请求才能获取10个帖子的详细信息(一个用于列表,十个用于缩略图)。是否可以在一个请求中获得此结果?


1
您是否使用register_rest_field为您的回复注册了新字段?
Benoti

@Benoti我将检查其文档。如果还有其他事情要问,我会再与您联系:)
VSB

没错,您在发布请求中没有图像日期,只有特色媒体的ID,并且在WP API的默认值上就需要一个新请求。
bueltge

如果添加_embed参数,则返回的post对象将包含有关精选媒体及其所有可用大小的所有详细信息。查看我的回复以获取示例。
耶苏斯·佛朗哥

Answers:


18

啊,我自己就是这个问题!虽然_embed很棒,但以我的经验来看,它非常慢,JSON的要点是要快:D

我在插件中有以下代码(用于添加自定义帖子类型),但我想您可以将其放在主题function.php文件中。

php

add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 
    'post', // Where to add the field (Here, blog posts. Could be an array)
    'featured_image_src', // Name of new field (You can call this anything)
    array(
        'get_callback'    => 'get_image_src',
        'update_callback' => null,
        'schema'          => null,
         )
    );
}

function get_image_src( $object, $field_name, $request ) {
  $feat_img_array = wp_get_attachment_image_src(
    $object['featured_media'], // Image attachment ID
    'thumbnail',  // Size.  Ex. "thumbnail", "large", "full", etc..
    true // Whether the image should be treated as an icon.
  );
  return $feat_img_array[0];
}

现在,在JSON响应中,您应该看到一个名为"featured_image_src":包含缩略图网址的新字段。

在此处阅读有关修改响应的更多信息:http :
//v2.wp-api.org/extending/modifying/

以下是有关register_rest_fieldwp_get_attachment_image_src()函数的更多信息:
1.)https://developer.wordpress.org/reference/functions/register_rest_field/
2.)https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

**注意:<?php ?>如果这是一个新的php文件,请不要忘记标签!


2
这很好用,并有助于不需要使用_embed,因为我只想要全尺寸的特色图像。我确实必须将其更改为:($object['featured_media'], 'fullsize', false);不要给我缩略图网址,而是可以通过functions.php完美地工作-谢谢!
约旦

1
所有与RES API端点的争执都让我想起为什么我喜欢GraphQL,并且我应该完成REST API和新的自定义解析器的包装;-)无论如何,这是一个聪明的解决方案,实际上我在生产中使用自定义端点来获取数据我需要(仅此)。
耶苏斯·佛朗哥

新插件有,http://mahditajik.ir/wp-json/wp/v2/media/<id>但是它有许多额外的数据,使响应速度变慢,所以我如何自定义REST api响应dto?
马赫迪

1
非常感谢,它帮助我完成了特色内容功能!:D
Atem18

1
我只是想让您知道,这使我的加载时间减少了2秒!非常感谢您和精心策划的书目!
GuiHarrison

7

只需将_embed查询参数添加到您的URL中以获取帖子,每个帖子对象将包括该_embedded.[wp:featuredmedia]对象,该对象包括所有图像,就像/media/$id资源一样。如果您想要一个特定的大小,只需通过其属性名称即可访问它,即:_embedded[wp:featuredmedia][0].media_details.sizes.full.source_url或对其缩略图进行访问:_embedded[wp:featuredmedia][0].media_details.sizes.thumbnail.source_url

也就是说,wp:featuredmedia嵌入式对象包含所有可用于帖子的尺寸的URL和详细信息,但是如果您只想要原始的特色图像,则可以使用此键中的值: post._embedded["wp:featuredmedia"][0].source_url

我在具有类似以下内容的网站中使用它(当然,请使用您自己的域):

$.get('https://example.com/wp-json/wp/v2/posts/?categories=3&_embed', 
    function(posts) { 
        var elems = '';
        posts.forEach(function(post){ 
            var link = post.link;
            var title = post.title.rendered;
            var pic = post._embedded["wp:featuredmedia"][0].source_url);
            elems += '<div class="this_week"><a href="' + link + '" target="_blank">';
            elems += '<img src="' + pic + '" title="' + title + '"/><span class="title">';
            elems += title + '</span></a></div>';
        });
        $('#blockbusters').html(elems);
    });
});

看到?无需两个查询,只需添加_embed为查询参数即可,然后您便拥有了为视图使用最佳大小所需的所有信息。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.