WordPress REST API – Post Comments

WordPress REST API allows you to post comments on any post using an HTTP POST request.

There are many parameters available depending on the requirement. In this tutorial, we will cover simple case to post a comment data on some particular post using post id.

Endpoint details to post a comment:

  • The ‘post’ parameter specify post id in the request.
  • The ‘content’ parameter specifies comment data.
  • POST – Use HTTP post request to send data.

Request Syntax:
POST site.com/wp-json/wp/v2/comments?post=12&content=MySampleComment

Success:
if comment posted successfully, it returns ‘201 Created’ response with some data,

Error:
It will send the following ‘401 Unauthorized’ response if comment posting failed. {"code":"rest_comment_login_required","message":"Sorry, you must be logged in to comment.","data":{"status":401}}

WordPress REST API v2: Allow anonymous comment post

WordPress v4.7.0 introduced a filter called ‘rest_allow_anonymous_comments’ which allows or does not allow anonymous comments to be created. it returns false by default. Therefore, you cannot create comments using WordPress REST API by default even if your WordPress settings allowed comment without login.

You can use the following filter in the theme’s ‘functions.php’ file to allow comments without login.

<?php
function wp_rest_allow_anonymous_comments_fx() {
    return true;
}
add_filter('rest_allow_anonymous_comments','wp_rest_allow_anonymous_comments_fx');
?>

Now, you should be able to post comments successfully using WordPress REST API. Depending on your WordPress discussion settings, either comment will be directly posted or held for moderation.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.