0

I want a function to check if the comment id has children (replies) or not.

5

Here's one example how to construct such a custom function:

/**
 * Check if a comment has children.
 *
 * @param  int $comment_id Comment ID
 * @return bool            Has comment children.
 */
function has_comment_children_wpse( $comment_id ) {
    return get_comments( [ 'parent' => $comment_id, 'count' => true ] ) > 0;
}

using the get_comments() function with the count attribute (to return the number of comments) and the parent attribute to find the children.

|improve this answer|||||
  • Could you provide a use example for this? For example, if has children then foo, else bar etc.? – Beaniie Mar 20 '19 at 14:18
  • 1
    @Beaniie do you mean: if ( has_comment_children_wpse( $comment_id ) ) { echo 'foo'; } else { echo 'bar'; } ? Note that you need to replace the $comment_id with an actual comment id. You could e.g. replace $comment_id with an actual id (e.g. 123) of a given comment to test. If you have access to a comment object, then on could try something like $comment->ID or get_comment_ID() within a comment loop. – birgire Mar 20 '19 at 20:03
  • Could you use it as such? if ( get_comments( [ 'parent' => $comment->ID, 'count' => true ] ) > 0 ) { echo 'foo'; } else { echo 'bar'; } – Beaniie Mar 21 '19 at 10:20
  • 1
    yes I think that would work too, if $comment is a comment object. – birgire Mar 21 '19 at 11:00
  • 1
    I'll give it a whirl, thanks for the assist. +1 – Beaniie Mar 21 '19 at 11:52
0

Here's another method in case you want to check if a comment has replies (children) within a get_comments() query. (You would likely not want to use birgire's method inside of a get_comments() query since you would be doing a get_comments() query inside of another get_comments() query.

My method is to use the WP_comment_query class's get_children() method:

$args = array(
'order'       => 'DESC',
'status'      => 'approve',
);

$comments = get_comments( $args );          
foreach ( $comments as $comment ) {
    $content = $comment->comment_content;
    $comment_children = $comment->get_children();

    if($comment_children){
        //code for comment with children
    } else {
        //code for comment without children 
    }
}
?>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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