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

WP REST API Get Post By Id With PHP

WordPress WP REST API V2 Tutorial get post by post id using php script.

wp rest api v2

WP REST API Get Posts By Tag

Wordpress WP REST API Tutorial Get Posts By Tag with php script

WP REST API V2 Auth

WP REST API Edit Post PHP cURL

Wordpess Tutorial WP REST API V2 Update Post by post id with PHP cURL

wp rest api v2

WP REST API Get Featured Image With Custom Endpoint

WP REST API Get Featured Image By Adding Custom Endpoint in Theme Function

WP REST API V2 Auth

WP REST API Create User With PHP cURL

WP REST API Create User With PHP cURL. PHP code example to create user for your wordpress website.