How to check if a comment has replies?

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

Topic comments Wordpress

Category Web


You can use this

$child_comments = get_comments(array(
    'post_id' => get_the_ID(),
    'status' => 'approve',
    'parent' => $comment->comment_ID,
));
if($child_comments){}

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 
    }
}
?>

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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.