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 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 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 Basic Authentication With PHP Curl

Wordpress Tutorial WP REST API Basic Authentication With PHP Curl

wp rest api v2

WP REST API Get Post By Slug With PHP

WordPress WP REST API Tutorial Get Post Data By Slug With PHP

WP REST API V2 Auth

WP REST API Delete Post With PHP cURL

Wordpress tutorial WP REST API Delete Post With PHP cURL with code example