@frontity/wp-comments
API reference of `@frontity/wp-comments` package
Comments package that adds integration for WordPress native comments.

Installation

Add the wp-comments package to your project:
1
npm i @frontity/wp-comments
Copied!

Settings

In WordPress

In order to use this package, you will need to add a single line of configuration to your Wordpress installation:
1
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Copied!
​This filter enables creating comments for anonymous users via the REST API.
You can add this snippet directly in your theme's functions.php file or use a Code Snippets plugin.

In Frontity

This package doesn't have any configuration. It just needs to be added to the packages array in frontity.settings.js.
frontity.settings.js
1
export default {
2
packages: ["@frontity/wp-comments"],
3
};
Copied!

Usage

Getting comments of a post

We can use the @comments/:id handler to fetch all the comments of a specific post (actions.source.fetch("@comments/60")).
This data will be populated to the state so then we can do state.source.get("@comments/60") to get the ID's of these comments.
1
>> frontity.state.source.get("@comments/60/")
2
{
3
"isFetching": false,
4
"isReady": true,
5
"link": "@comments/60/",
6
"route": "@comments/60/",
7
"query": {},
8
"page": 1,
9
"postId": 60,
10
"items": [
11
{
12
"type": "comment",
13
"id": 285
14
},
15
...,
16
​
17
{
18
"type": "comment",
19
"id": 274,
20
"children": [
21
{
22
"type": "comment",
23
"id": 276
24
}
25
]
26
},
27
...
28
],
29
"total": 32,
30
"totalPages": 1,
31
"type": "comments",
32
"isComments": true
33
}
Copied!
With each ID we can get the details from the state at state.source.comment[id]`.
1
>> frontity.state.source.comment[285]
2
{
3
"id": 285,
4
"parent": 0,
5
"author": 0,
6
"author_name": "mario",
7
"author_url": "",
8
"date": "2020-07-31T11:30:25",
9
"content": {
10
"rendered": "<p>Let&#8217;s see it</p>\n"
11
},
12
"link": "/2016/the-beauties-of-gullfoss/comment-page-5/#comment-285",
13
"type": "comment",
14
"author_avatar_urls": {...},
15
...
16
}
17
}"
Copied!
Take a look at this diagram to learn more about this.

Sending new comments for a post

Every post with a comments form (to send comments) will use state.comments.forms[postId] to store the data of the comment and the submission status.
The data at state.comments.forms[postId] can be updated through the action actions.comments.updateFields().
1
>> frontity.actions.comments.updateFields(60, {
2
content: "Hello world!",
3
authorName: "Jamie",
4
authorEmail: "[email protected]"
5
});
6
>> frontity.state.comments.forms[60].fields
7
{
8
"content": "Hello world!",
9
"authorName": "Jamie",
10
"authorEmail": "[email protected]"
11
}
Copied!
To send new comments you can use the action actions.comments.submit() which will send the data available at state.comments.forms[postId].fields.
The submission status will be stored under under state.comments.forms[postId] and if there are errors they will be available at the properties errorMessage, errorCode and errorStatusCode.
1
>> frontity.state.comments.forms[60]
2
{
3
"fields": {
4
"content": "Nice post!",
5
"authorName": "Johnny",
6
"authorEmail": "[email protected]"
7
},
8
"isSubmitting": false,
9
"isSubmitted": false,
10
"isError": true,
11
"errorMessage": "Invalid parameter(s): author_email",
12
"errorCode": "rest_invalid_param",
13
"errorStatusCode": 400
14
}
Copied!
Take a look at this diagram to learn more about this.

API Reference

Handlers

@comments/:id

This wp-source handler gets all comments published in the specified post (using its ID) and creates a tree structure with comments and their replies in the data object.
For example, to fetch all comments that belong to the post with ID 60 you would do:
1
await actions.source.fetch("@comments/60");
Copied!
This would fetch all comments associated with that post and populate a data object inside the state (frontity.state.source.data["@comments/60/"]) with a tree structure of comments and replies, sorted by date (most recent first).
Have a look at the section Getting comments of a post to learn more
To access the fetched comments you could use something similar to this example:
1
const Comments = connect(({ postId, state }) => {
2
// Get comments from state.
3
const data = state.source.get(`@comments/${postId}`);
4
​
5
// Utility to render comments and replies recursively.
6
const renderComments = (items) =>
7
items.map(({ id, children }) => (
8
// You should define your own <Comment/> component!
9
<Comment key={id}>
10
{/* Render replies */}
11
{children && renderComments(children)}
12
</Comment>
13
));
14
​
15
// Render comments if data is ready.
16
return data.isReady ? renderComments(data.items) : null;
17
});
Copied!

State

state.comments.forms[postId]

The wp-comments package stores a map of objects by post ID in state.comments.forms. Each of these objects represents one comment form. These objects are intended to be used as the state of React <form> components and contain the input values as well as the submission status. They have the following properties:
Name
Type
Description
fields
​object​
Form fields with their values.
isSubmitting
boolean
The comment hasn't been received by WP yet.
isSubmitted
boolean
The comment has been received.
isError
boolean
The request has failed.
errorMessage
string
Failure reason.
errorCode
string
The error code. Those are defined internally in the WordPress REST API. Example: rest_comment_invalid_post_id
errorStatusCode
number
The HTTP status code that might have been received from the WordPress REST API.

state.comments.forms[postId].fields

The following map of fields, representing the current field values that have been input in the form rendered in the given post. The content of this property is updated using the updateFields() action described later.
Name
Type
Required
Description
content
string
yes
Content of the comment.
authorName
string
no
Author's name.
author
number
no
The ID of the author.
authorEmail
string
no
Author's email.
authorURL
string
no
URL of the author's site.
parent
number
no
ID of the comment to which this one responds. Default Value: 0
See the section Sending new comments for a post to learn more.

state.source.comment[id]

This is the portion of the state where the comments are stored after being fetched from the REST API or POSTed through the comments.submit() action.
Thanks to the handler @comments/:id you can get the ID's of the comments in a specific post.
With this list of ID's you can get the details for each one at state.source.comment[id].
See the section Getting comments of a post to learn more.
Example
1
const data = state.source.get(`@comments/${postId}`);
2
​
3
data.items
4
.map(({ id }) => {
5
// For each ID we can get the details of each comment at state.source.comment[id]
6
const authorName = state.source.comment[id].author_name || "Anonymous";
7
const content = state.source.comment[id].content.rendered;
8
const date = state.source.comment[id].date;
9
return { id, authorName, content, date };
10
})
11
.forEach(console.log);
Copied!
Check a fully working example of this in this wp-comments demo.

Actions

actions.comments.updateFields()

Update the fields of the form specified by postId. This action simply updates what is stored in state.comments.forms[postId].fields with the given values.
If no fields are specified, the form fields are emptied.
These fields will be used by actions.comments.submit() when submitting the comment.
Syntax
1
(postId: number, comment: object) => Promise;
Copied!
Arguments
Name
Type
Required
Description
postId
number
yes
The ID of the post where the comment will be published.
comment
object
no
Object representing the fields of the comment to be updated. The fields of this object are the same than the ones at state.comments.forms[postId].fields​
1
actions.comments.updateFields(60, {
2
content: "Hello world!",
3
});
Copied!
See the section Sending new comments for a post to learn more.

actions.comments.submit()

This asynchronous action publishes a new comment for the post specified by postId. It submits the fields stored in the respective form (i.e. state.comments.forms[postId]) or the fields passed as a second argument. If fields are passed, those replace the current values stored in state.comments.forms[postId].fields.
After calling this action, you can access state.comments.forms[postId].isSubmitted property (described above) to determine the submission status.
Take into account that this action does not validate input. This means requests are made even though some fields are empty or have invalid values. If that is the case, WordPress will return an error message and populate the error status accordingly.
Syntax
1
(postId: number, comment: object) => Promise;
Copied!
Arguments
Name
Type
Required
Description
postId
number
yes
The ID of the post where the comment will be published.
comment
object
no
Object representing the comment. The fields of this object are the same than the ones at state.comments.forms[postId].fields​
1
// Submit the comment to the post with ID 60
2
// using the values stored in `state.comments.forms[60].fields`.
3
await actions.comments.submit(60);
4
​
5
// Submit the comment to the post with ID 60
6
// using the values passed as the second argument.
7
await actions.comments.submit(60, {
8
content: "This is a comment example. Hi!",
9
authorName: "Frontibotito",
10
authorEmail: "[email protected]",
11
});
Copied!
Take a look at the section Sending new comments for a post to learn more.

Demo

This short video demonstrates the usage of the @frontity/wp-comments package.
The project used in the video is available here.
Last modified 6mo ago