API Reference
  • Introduction
  • 💻CLI Commands
    • Create commands
      • create
      • create-package
    • Run commands
      • dev
      • serve
    • Build commands
      • build
    • Extra commands
  • 🍱Packages
    • 💙Core package
      • frontity
    • ⚡Features packages
      • @frontity/wp-source
      • @frontity/tiny-router
      • @frontity/html2react
      • @frontity/head-tags
      • @frontity/yoast
      • @frontity/google-ad-manager
      • @frontity/smart-adserver
      • analytics packages
        • @frontity/google-analytics
        • @frontity/google-tag-manager-analytics
        • @frontity/comscore-analytics
      • @frontity/wp-comments
    • 📚Collections packages
      • @frontity/components
      • @frontity/hooks
        • Infinite Scroll Hooks
        • Intersection Observer Hooks
    • 🎨Themes Packages
      • @frontity/twentytwenty-theme
      • @frontity/mars-theme
  • 🔌WordPress Plugins
    • REST API - Head Tags
    • Frontity Embedded Mode
Powered by GitBook
On this page
  • Installation
  • Settings
  • In WordPress
  • In Frontity
  • Usage
  • Getting comments of a post
  • Sending new comments for a post
  • API Reference
  • Handlers
  • State
  • Actions
  • Demo

Was this helpful?

  1. Packages
  2. Features packages

@frontity/wp-comments

API reference of `@frontity/wp-comments` package

Previous@frontity/comscore-analyticsNextCollections packages

Last updated 4 years ago

Was this helpful?

Comments package that adds integration for WordPress native comments.

Installation

Add the wp-comments package to your project:

npm i @frontity/wp-comments

Settings

In WordPress

In order to use this package, you will need to add a single line of configuration to your Wordpress installation:

add_filter( 'rest_allow_anonymous_comments', '__return_true' );

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

export default {
  packages: ["@frontity/wp-comments"],
};

Usage

Getting comments of a post

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.

>> frontity.state.source.get("@comments/60/")
{
  "isFetching": false,
  "isReady": true,
  "link": "@comments/60/",
  "route": "@comments/60/",
  "query": {},
  "page": 1,
  "postId": 60,
  "items": [
    {
      "type": "comment",
      "id": 285
    },
    ...,

    {
      "type": "comment",
      "id": 274,
      "children": [
        {
          "type": "comment",
          "id": 276
        }
      ]
    },
  ...
  ],
  "total": 32,
  "totalPages": 1,
  "type": "comments",
  "isComments": true
}
>> frontity.state.source.comment[285]
{
  "id": 285,
  "parent": 0,
  "author": 0,
  "author_name": "mario",
  "author_url": "",
  "date": "2020-07-31T11:30:25",
  "content": {
    "rendered": "<p>Let&#8217;s see it</p>\n"
  },
  "link": "/2016/the-beauties-of-gullfoss/comment-page-5/#comment-285",
  "type": "comment",
  "author_avatar_urls": {...},
  ...
  }
}"

Sending new comments for a post

>> frontity.actions.comments.updateFields(60, {
  content: "Hello world!",
  authorName: "Jamie",
  authorEmail: "jamie@gmail.com"
});
>> frontity.state.comments.forms[60].fields
{
  "content": "Hello world!",
  "authorName": "Jamie",
  "authorEmail": "jamie@gmail.com"
}
>> frontity.state.comments.forms[60]
{
  "fields": {
    "content": "Nice post!",
    "authorName": "Johnny",
    "authorEmail": "johnny@gmail"
  },
  "isSubmitting": false,
  "isSubmitted": false,
  "isError": true,
  "errorMessage": "Invalid parameter(s): author_email",
  "errorCode": "rest_invalid_param",
  "errorStatusCode": 400
}

API Reference

Handlers

@comments/:id

For example, to fetch all comments that belong to the post with ID 60 you would do:

await actions.source.fetch("@comments/60");

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).

To access the fetched comments you could use something similar to this example:

const Comments = connect(({ postId, state }) => {
  // Get comments from state.
  const data = state.source.get(`@comments/${postId}`);

  // Utility to render comments and replies recursively.
  const renderComments = (items) =>
    items.map(({ id, children }) => (
      // You should define your own <Comment/> component!
      <Comment key={id}>
        {/* Render replies */}
        {children && renderComments(children)}
      </Comment>
    ));

  // Render comments if data is ready.
  return data.isReady ? renderComments(data.items) : null;
});

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

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

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

state.source.comment[id]

With this list of ID's you can get the details for each one at state.source.comment[id].

Example

const data = state.source.get(`@comments/${postId}`);

data.items
  .map(({ id }) => {
    // For each ID we can get the details of each comment at state.source.comment[id]
    const authorName = state.source.comment[id].author_name || "Anonymous";
    const content = state.source.comment[id].content.rendered;
    const date = state.source.comment[id].date;
    return { id, authorName, content, date };
  })
  .forEach(console.log);

Actions

actions.comments.updateFields()

If no fields are specified, the form fields are emptied.

Syntax

(postId: number, comment: object) => Promise;

Arguments

Name

Type

Required

Description

postId

number

yes

The ID of the post where the comment will be published.

comment

object

no

actions.comments.updateFields(60, {
  content: "Hello world!",
});

actions.comments.submit()

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

(postId: number, comment: object) => Promise;

Arguments

Name

Type

Required

Description

postId

number

yes

The ID of the post where the comment will be published.

comment

object

no

// Submit the comment to the post with ID 60
// using the values stored in `state.comments.forms[60].fields`.
await actions.comments.submit(60);

// Submit the comment to the post with ID 60
// using the values passed as the second argument.
await actions.comments.submit(60, {
  content: "This is a comment example. Hi!",
  authorName: "Frontibotito",
  authorEmail: "frontibotito@frontity.com",
});

Demo

This short video demonstrates the usage of the @frontity/wp-comments package.

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 plugin.

We can use the handler to fetch all the comments of a specific post (actions.source.fetch("@comments/60")).

With each ID we can get the details from the state at `.

Take a look at this to learn more about this.

Every post with a comments form (to send comments) will use to store the data of the comment and the submission status.

The data at state.comments.forms[postId] can be updated through the action .

To send new comments you can use the action which will send the data available at .

The submission status will be stored under under and if there are errors they will be available at the properties errorMessage, errorCode and errorStatusCode.

Take a look at this to learn more about this.

This 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.

Have a look at the section to learn more

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 action described later.

See the section to learn more.

This is the portion of the state where the comments are stored after being fetched from the REST API or POSTed through the action.

Thanks to the handler you can get the in a specific post.

See the section to learn more.

Check a fully working example of in .

Update the fields of the form specified by postId. This action simply updates what is stored in with the given values.

These fields will be used by when submitting the comment.

Object representing the fields of the comment to be updated. The fields of this object are the same than the ones at

See the section to learn more.

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 .

Object representing the comment. The fields of this object are the same than the ones at

Take a look at the section to learn more.

The project used in the video is available .

🍱
⚡
This filter
Code Snippets
diagram
diagram
wp-source
this
this wp-comments demo
here
Installation
Settings
In WordPress
In Frontity
Usage
Getting comments of a post
Sending new comments for a post
API Reference
Handlers
@comments/:id
State
state.comments.forms[postId]
state.comments.forms[postId].fields
state.source.comment[id]
Actions
actions.comments.updateFields()
actions.comments.submit()
Demo
@comments/:id
state.source.comment[id]
state.comments.forms[postId]
actions.comments.updateFields()
actions.comments.submit()
state.comments.forms[postId].fields
state.comments.forms[postId]
Getting comments of a post
updateFields()
Sending new comments for a post
comments.submit()
ID's of the comments
@comments/:id
Getting comments of a post
state.comments.forms[postId].fields
actions.comments.submit()
Sending new comments for a post
state.comments.forms[postId].fields
Sending new comments for a post
object
state.comments.forms[postId].fields
state.comments.forms[postId].fields