I'm trying to replicate the option in WordPress's settings page that says:

[x] Break comments into pages with ((5)) top level comments per page and the ((first)) page displayed by default

Right now I have the following comment query, but it only displays 5 comments, also counting the replies.

The behavior I want is 5 top-level comments, and all the replies those top-level comments might have. How do I achieve this?

Current Code

$args = array(
    'post_id' => $post_id,
    'type' => 'comment',
    'status' => 'approve',

    'number' => 5,
    'hierarchical' => 'threaded'
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query($args);

Output

Total of 5 comments

Comment 1

  • Reply to comment 1
  • Reply to comment 1

Comment 2

Comment 3

Desired Output

5 top-level comments and all their replies

Comment 1

  • Reply to comment 1
  • Reply to comment 1

Comment 2

Comment 3

  • Reply to comment 3
  • Reply to comment 3
  • Reply to comment 3

Comment 4

Comment 5

  • Reply to comment 5
up vote 3 down vote accepted

Updated

The hierarchical parameter controls whether to include comment descendants in the comments results.

From the inline docs we have that it accepts the following values:

  • 'threaded' returns a tree, with each comment's children stored in a children property on the WP_Comment object.
  • 'flat' returns a flat array of found comments plus their children.
  • false to leave out descendants.

It also says that

The parameter is ignored (forced to false) when $fields is 'ids' or 'counts'.

Both the 'threaded' and 'flat' options makes use of the WP_Comment_Query::fill_descendants() method:

Instead of calling get_children() separately on each child comment, we do a single set of queries to fetch the descendant trees for all matched top-level comments.

but the threaded option has additional snippet that uses the add_child() method of the WP_Comment object to construct the children property.


As @Swen mentioned in comments, one should use the 'threaded' option.

It looks like the true value would in fact give the same as the 'flat' option.

  • WP_Comment_Query::fill_descendants() looks great! But I'm unsure how to use it... Could you provide an example? – Swen Apr 27 '17 at 11:42
  • Also note that 'hierarchical' => true is invalid and it should be 'hierarchical => 'threaded'. – Swen Apr 27 '17 at 13:36

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.