FieldtypeComments class

Stores user-posted comments for a page

The value is a CommentArray containing Comment objects. Provides built-in rendering for comment lists and submission forms.

Value type

CommentArray (extends PaginatedArray). Each item is a Comment (extends WireData).

Each comment's status is stored in a $comment->status property, which can have any one of the following values:

Status constantValueMeaning
Comment::statusSpam-2Identified as spam
Comment::statusPending0Awaiting moderation
Comment::statusApproved1Approved and visible
Comment::statusFeatured2Approved and featured

Each Comment object also includes several other properties (cite, text, email, etc.), which are outlined in the section below.

Getting and setting values
// Iterate comments on a page
foreach($page->comments as $comment) {
    echo $comment->cite;        // poster name
    echo $comment->text;        // comment text
    echo $comment->email;       // poster email (not shown publicly by default)
    echo $comment->website;     // poster website
    echo $comment->created;     // unix timestamp
    echo $comment->status;      // see Comment::status* constants
    echo $comment->stars;       // 1–5 or 0 if stars not enabled
    echo $comment->upvotes;
    echo $comment->downvotes;
    echo $comment->depth;       // nesting depth when threading enabled (0=top level)
    // See Comment.php for the full list of Comment properties
}

// Add a new comment programmatically (import, no filtering or notifications)
$comment = new Comment();
$comment->cite = 'John Smith';
$comment->email = 'john@example.com';
$comment->text = 'Great article!';
$comment->status = Comment::statusApproved;
$field = $fields->get('comments'); // get the CommentField object
$field->addComment($page, $comment, false); // false = no filtering/notifications

// Add a comment from user input (triggers moderation filtering and notifications)
$field->addComment($page, $comment, true);

// Update a comment property
$field->updateComment($page, $comment, ['status' => Comment::statusApproved]);

// Delete a comment
$field->deleteComment($page, $comment);

// Get a comment by ID
$comment = $field->getCommentByID($page, 123);

// Get a comment by its approval code (e.g. from a notification email link)
$comment = $field->getCommentByCode($page, $code);

// Count comments on a page
$total = $field->getNumComments($page);
$approved = $field->getNumComments($page, ['minStatus' => Comment::statusApproved]);

// Find comments across all pages in the field (database query)
$comments = $field->find('status=1, sort=-created, limit=10');
$comments = $field->find("pages_id=$page->id, status>=1");
$comments = $field->find('stars>=4, status=1, sort=-created');

// Vote on a comment (requires useVotes enabled on field)
$field->voteComment($page, $comment, true);   // upvote
$field->voteComment($page, $comment, false);  // downvote

// Threaded comments (requires depth > 0 on field)
$parent   = $comment->parent;    // parent Comment or null
$children = $comment->children;  // CommentArray of immediate children
$parents  = $comment->parents;   // CommentArray of all ancestors

// Store/retrieve arbitrary extra data on a comment (stored in the meta column)
$comment->meta('key', 'value');          // set
$value = $comment->meta('key');          // get
$all = $comment->meta();                 // get all as array
$comment->meta(['key1' => 1, 'key2' => 2]); // set multiple at once
$field->updateComment($page, $comment, ['meta' => $comment->meta()]); // save
Selectors

Page-level selectors (via $pages->find()):

// Pages with at least one approved comment
$pages->find('comments.count>0');

// Match comment text content
$pages->find('comments.data*=keyword');

Comment-level selectors (via $field->find()):

This enables you to find comments regardless of which page they appear on.

// Approved comments, newest first
$field->find('status=1, sort=-created, limit=20');

// Featured comments
$field->find('status=' . Comment::statusFeatured);

// Pending moderation
$field->find('status=' . Comment::statusPending);

// Comments on a specific page only
$field->find("pages_id=$page->id, status>=1");

// Comments with star rating of 4 or above
$field->find('stars>=4, status=1');

Examples of supported find() selector fields: id, status, flags, created, pages_id, parent_id, created_users_id, upvotes, downvotes, stars, text, cite, email, website, ip, user_agent.

Output / markup
// Render the comment list (uses CommentList class)
echo $page->comments->render();

// Render only the submission form (uses CommentForm class)
echo $page->comments->renderForm();

// Render both list and form
echo $page->comments->renderAll();

// Pass options to the renderer
echo $page->comments->render([
    'dateFormat' => 'Y-m-d',
    'useGravatar' => '',
]);

// Get object instances for full control
$commentList = $page->comments->getCommentList();
$commentForm = $page->comments->getCommentForm();
echo $commentList->render();
echo $commentForm->render();

Rendering can be customized by extending CommentList or CommentForm (or using the CommentListCustom / CommentFormCustom drop-in classes).

Notes
  • Moderation constants (moderate field setting):

    • FieldtypeComments::moderateNone (0) — no moderation; all comments published immediately
    • FieldtypeComments::moderateAll (1) — all comments require manual approval
    • FieldtypeComments::moderateNew (2) — only first-time commenters require approval
  • Votes constants (useVotes field setting):

    • FieldtypeComments::useVotesNo (0) — voting disabled
    • FieldtypeComments::useVotesUp (1) — upvotes only
    • FieldtypeComments::useVotesAll (2) — upvotes and downvotes
  • Stars constants (useStars field setting):

    • FieldtypeComments::useStarsNo (0) — disabled
    • FieldtypeComments::useStarsYes (1) — optional
    • FieldtypeComments::useStarsRequired (2) — required on submission
  • addComment($page, $comment, $send): pass $send=true when the comment comes from live user input (triggers moderation filtering and notification emails); pass $send=false for programmatic imports where no filtering or emails should run.

  • Database columns (one row per comment): id, pages_id, parent_id, data (comment text, FULLTEXT indexed), sort, status, flags, created, email, cite, website, ip, user_agent, created_users_id, code, subcode, upvotes, downvotes, stars, meta.

  • Compatible fieldtypes: FieldtypeComments only.

API reference: methods, hooks

Click any linked item for full usage details and examples. Hookable methods are indicated with the icon. In addition to those shown below, the FieldtypeComments class also inherits all the methods and properties of: FieldtypeMulti, Fieldtype, WireData and Wire.

Show class?     Show args?       Only hookable?    

Common

NameReturnSummary 
FieldtypeComments::addComment(Page $page, Field $field, Comment $comment, bool $send)
bool

Add new comment

 
FieldtypeComments::checkVoteAction($page)
array

Check the request for a vote action

 
FieldtypeComments::count($selectorString)
int

Given a field and a selector, return total quantity of comments matching the selector

 
FieldtypeComments::deleteComment(Page $page, Field $field, Comment $comment)
bool

Delete a given comment

 
FieldtypeComments::deleteField(Field $field)
bool

Delete the given field, which implies: drop the table $field->table

FieldtypeComments::exportValue(Page $page, Field $field, $value)
array

Export value

FieldtypeComments::find($selectorString)
CommentArray int

Given a field and a selector, find all comments matching the selector

 
FieldtypeComments::findComments($field, string $selectorString)
CommentArray

Find comments, static version for backwards compatibility

 
FieldtypeComments::getBlankValue($page, $field)
None 
FieldtypeComments::getCommentByCode($page, $field, $code)
Comment null

Given a comment code or subcode, return the associated comment ID or 0 if it doesn't exist

 
FieldtypeComments::getCommentByID($page, $field, int $id)
Comment null

Get a comment by ID or NULL if not found

 
FieldtypeComments::getCommentParents(Page $page, Field $field, Comment $comment)
CommentArray

Get parent comments for given Comment

 
FieldtypeComments::getCommentsByID($field, array $ids)
CommentArray

Get multiple comments by ID

 
FieldtypeComments::getCommentsFields()
array Field null

Return comments field(s)

 
FieldtypeComments::getConfigInputfields(Field $field)
InputfieldWrapper

Configuration that appears with each Comments fieldtype

FieldtypeComments::getDatabaseSchema(Field $field)
array

Schema for the Comments Fieldtype

 
FieldtypeComments::getFieldClass()
None 
FieldtypeComments::getInputfield($page, $field)
None 
FieldtypeComments::getLoadQueryAutojoin(Field $field, DatabaseQuerySelect $query)
null

For FieldtypeMulti interface, return NULL to indicate that the field is not auto-joinable

 
FieldtypeComments::getMatchQuery(PageFinderDatabaseQuerySelect $query, string $table, string $subfield, string $operator, mixed $value)
DatabaseQuery DatabaseQuerySelect

Update a query to match the text with a fulltext index

 
FieldtypeComments::getNotifyEmails(Page $page, Field $field)
array

Get emails (and other data) of people that should be notified for a given Page’s comments

 
FieldtypeComments::getNumComments(Page $page, Field $field)
int

Get number of comments for Page, optionally limited by specific $options

 
FieldtypeComments::importValue(Page $page, Field $field, array $value)
array string

Import value

FieldtypeComments::sanitizeValue($page, $field, $value)
None 
FieldtypeComments::savePageField(Page $page, Field $field)
bool

Per the Fieldtype interface, Save the given Field from the given Page to the database

FieldtypeComments::sendNotifyEmails(Page $page, Field $field, Comment $comment, array $emailsData)
int

Get emails (and other data) of people that should be notified for a given Page’s comments

FieldtypeComments::sleepValue(Page $page, Field $field, $value)
array

Given an 'awake' value, as set by wakeupValue, convert the value back to a basic type for storage in DB.

FieldtypeComments::updateComment(Page $page, Field $field, Comment $comment, array $properties)
bool

Update specific properties for a comment

FieldtypeComments::voteComment(Page $page, Field $field, Comment $comment)
bool

Add a vote to the current comment from the current user/IP

 
FieldtypeComments::wakeupValue(Page $page, Field $field, $value)
CommentArray

Given a raw value (value as stored in DB), return the value as it would appear in a Page object

FieldtypeComments::wired()
None 

Deleting

Additional methods and properties

In addition to the methods and properties above, FieldtypeComments also inherits the methods and properties of these classes:

API reference based on ProcessWire core version 3.0.259