WP REST API Create Comment Into A Post

By | June 13, 2017

WP REST API Tutorial Create Comment Into A Post.

WP Rest APi ( WP-JSON ) also can be used to create a comment into a post. In this wp json tutorial I will write a php code example to create a comment using php file_get_contents method. This code need basic authentication plugin installed and enabled for a wordpress website.

WP REST API Create Comment as Author

$post_id  	= 532;
$url 		= 'http://localhost/wp/wp-json/wp/v2/comments/?post='.$post_id;
$username 	= 'admin';
$password 	= 'admin';

$postdata = http_build_query(
	array(
        'author' 	=>  '1',	
	'content' 	=> 'This is comment content',	
	'status' 	=> 'approved', // change into hold for moderation
    )
);


//another parameters http://v2.wp-api.org/reference/comments/

$context = stream_context_create(array(
	'http' 	=> array(
	'method'  	=> 'POST',
	'header'	=> "Content-Type: application/x-www-form-urlencoded\r\n".
			"Authorization: Basic " . base64_encode("$username:$password"),		
	'content' 	=> $postdata
	)
));

$data = file_get_contents($url, false, $context);

 

WP REST API Create Comment as Guest / Visitor

To create a comment as non author / administrator change post data variable from script above with this code bellow.

$postdata = http_build_query(
 array(
 'author_name' => 'Change Name',
 'author_email' => 'change_email@yahoo.com',
 'author_url' => 'changewebsite.net',
 'content' => 'This is a comment content', 
 'status' => 'approved', // change into hold for moderation
 )
);

That’s an easy tutorial with code example of creating comment with wp rest api using php file_get_contents(). You also can use cURL module to run the same function.

Related Posts

WP REST API V2 Auth

WP REST API Upload Image Media

Wordpress WP REST API V2 tutorial and code example upload image / media with PHP cURL

wp rest api v2

WP REST API Create Category PHP cURL

Wordpress Tutorial WP REST API V2 Create Category With PHP cURL with code example

wp rest api v2

WP Rest API V2 Introduction

WP Rest API V2 Introduction. WordPress is one of the most used content management system (CMS) in the world.

wp rest api v2

WP REST API Get Posts By Category

WordPress REST API tutorial get posts by category id with php script

WP REST API V2 Auth

Autocomplete WordPress Search Form With WP REST API

WordPress Tutorial Create Autocomplete Search Form Using WP REST API V2 With Code Example