How To Create A Post With WP JSON REST API Through Ajax

A few months ago, someone started a project called WP JSON REST API and claimed it’ll be core part of WordPress in the future.

Lately, I was playing nodejs and I have some troubles with its xmlrpc module. Then, I thought of this project so I decided to give it a shot.

I spent some time looking at the document and the source code.

After some struggles, I managed to create a post with Ajax. :)

                var content = {
                               'title':article.title,
				'content':article.content,
				'status': 'publish'
			}
						
		var headers = {
						'Authorization':'Basic YWRtaW46MTIzNDU2'
						}
		var options = {
						data:JSON.stringify(content),
						url:'http://www.test.com/wp-json.php/posts/',
						headers:headers,
						type:'POST',
						dataType:'json',
						contentType: 'application/javascript',
						complete:function(xhr,status){
							console.log(xhr);
							console.log(status);

						}
					}
		Zepto.ajax(options);


#1, When creating a post, you need to do 401 Authorization. It’s interesting that zepto.js Ajax supports username and password and the final URL will be http:[email protected]:www.test.com . But from the response, WordPress or the JSON API doesn’t support this kind of Authorization. So I have to do header instead.

#2, I have no idea why it get rids of “post_” prefix and WordPress XMLRPC has “post_”. It would be nice to keep params consistent.

#3, You need to JSON.stringify the content structure and make sure the content type is javascript. It’s using http_raw_post_data to retrieve the data. It takes me a while to figure it out.

#4, I’ve read the source code on insert_post a few times and it looks like it doesn’t supports terms_name even though it says so in the document.

Because of #4, I can’t set category or tags to the created post. So I decided to go back to XMLRPC….. But I’m sure it’ll be fixed when integrate into WordPress core.

Share and Enjoy

    FacebookTwitterGoogle PlusLinkedInStumbleUponPinterestRedditTumblrDiggEmailPrint

Related Posts