WP REST API 如何上传特色图片? [英] WP REST API How to upload featured image?

查看:53
本文介绍了WP REST API 如何上传特色图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WP REST API 插件 V2 (http://wp-api.org/).

I'm using the WP REST API plugin V2 (http://wp-api.org/).

API 能否上传精选图片并生成相关元数据?

Can the API upload a featured image and generate the related meta data?

我知道我可以上传图片附件 (POST/wp-json/wp/v2/media) 然后更新相关文章 (PUT/wp-json/wp/v2/posts/ID) 并使其成为featured_image" 指向附件 id 的关键点.

I know I can upload an image attachment (POST /wp-json/wp/v2/media) and then update the related article (PUT /wp-json/wp/v2/posts/ID) and make its "featured_image" key point to the attachment id.

但这是正确的做法吗?

上传后是否可以生成特色图片的不同(调整大小)版本,或者这是否需要自定义端点?

Is it possible to generate different (resized) versions of the featured image after upload, or does this require a custom endpoint?

推荐答案

我知道我可以上传图片附件 (POST/wp-json/wp/v2/media) 然后更新相关文章 (PUT/wp-json/wp/v2/posts/ID) 并使其成为featured_image" 指向附件 ID 的关键点.但这是正确的做法吗?

I know I can upload an image attachment (POST /wp-json/wp/v2/media) and then update the related article (PUT /wp-json/wp/v2/posts/ID) and make its "featured_image" key point to the attachment id. But is this the right way to do this?

据我所知,这是要走的路.WP API 文档在解释所有这些方面有点"短.这其中涉及了相当多的挫败感,但最终这正是我让它工作的方式.

As far as I can tell thats the way to go. WP API docs is "a bit" short on explaining all this. And quite some frustration was involved but in the end thats exactly how I got it working.

所以首先将媒体上传到端点 POST/wp-json/wp/v2/media,使用以下 HTTP 标头和文件内容作为数据:

So first upload the media to endpoint POST /wp-json/wp/v2/media, with the following HTTP headers and the file contents as data:

            'CURLOPT_HTTPHEADER' => [
            'Content-type: application/json',
            'Authorization: Basic ' . $base64Credentials,
            'Content-Disposition: attachment; filename="acme.png"'
            ]

这里的重点是 Content-Disposition 标头.此调用应返回媒体 ID,您现在需要它来调用 POST/wp-json/wp/v2/posts/{$existingPostId}.

The catch here was the Content-Disposition header. This call should return the media ID, which you will need now for calling POST /wp-json/wp/v2/posts/{$existingPostId}.

相同的标题,但没有 Content-Disposition.这次的数据应该是 JSON 编码的 {"featured_media": 156}

Same headers but without the Content-Disposition. This time the data should be JSON encoded {"featured_media": 156}

(您不必直接使用 CURL.只需确保将 HTTP 标头传递到请求中即可)

(you dont have to use CURL directly. Just be sure to pass in the HTTP headers into the request)

这篇关于WP REST API 如何上传特色图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆