最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to create a post using REST API with sending data as a JSON body?

programmeradmin1浏览0评论

I am able to create posts on my WordPress website using it's REST API with the below curl request format. Website uses basic auth plugin for the authentication process.

curl --user "username:password" -X POST -i ;content=MyContent

However, my problem is I need to set custom fields of the post when creating a post using REST API. I tried to send data as a JSON body using the below command and it didn't work. It just returns all the posts without creating a new post and also without giving any error.

curl --user "username:password" -X POST -i -d '{"title":"NEw tiitle"}'

I have tried sending post creation requests to my website using the Postman service also and the same thing happened. Could anyone please help me to solve this problem? Thanks in advance!

I am able to create posts on my WordPress website using it's REST API with the below curl request format. Website uses basic auth plugin for the authentication process.

curl --user "username:password" -X POST -i https://mywebsite/wp-json/wp/v2/posts?title=myTitle&content=MyContent

However, my problem is I need to set custom fields of the post when creating a post using REST API. I tried to send data as a JSON body using the below command and it didn't work. It just returns all the posts without creating a new post and also without giving any error.

curl --user "username:password" -X POST -i https://mywebsite/wp-json/wp/v2/posts -d '{"title":"NEw tiitle"}'

I have tried sending post creation requests to my website using the Postman service also and the same thing happened. Could anyone please help me to solve this problem? Thanks in advance!

Share Improve this question asked Feb 6, 2021 at 15:09 Priyantha BuddhikaPriyantha Buddhika 133 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

That's strange, but nonetheless, you should know that whether you use cURL, PHP, JS, etc., if you're sending a JSON data, then you should set the Content-Type header to application/json.

And via the cURL command line, you can use the -H option:

curl --user "username:password" -X POST \
-H "Content-Type: application/json" \
-i https://example/wp-json/wp/v2/posts \
-d '{"title": "foo bar", "content": "test"}'

Also, if you're using Windows, you may need to use the double quotes instead of single quotes with the -d option. So the above would be: ( note I used the caret (^) symbol and not backslash )

curl --user "username:password" -X POST ^
-H "Content-Type: application/json" ^
-i https://example/wp-json/wp/v2/posts ^
-d "{\"title\": \"Windows test\", \"content\": \"test\"}"
发布评论

评论列表(0)

  1. 暂无评论