How is it possible to get top comment from all children?

I’m able to check whether or not the parent comment is the top comment:

$comment_obj = get_comment( $comment_ID );
$parent_ID = $comment_obj->comment_parent;

But I’d like to be able to get the top comment no matter if I am posting a child or grandchild etc. I can’t find much information of retrieving parent/top comments at all?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could adapt get_post_acestors(), and write a similar function for comments. Here is an example that returns the top comment’s id or false. Not tested!

function get_root_comment( $comment_id ) {
    
    $comment = get_comment( $comment_id );  
 
    if ( ! $comment 
        || empty( $comment->comment_parent ) 
        || $comment->comment_parent == $comment_id 
    ) {
        return false;
    }
 
    $ancestors   = [];   
    $id          = $comment->comment_parent;
    $ancestors[] = $id;
 
    while ( $ancestor = get_comment( $id ) ) {
        
        if ( empty ( $ancestor->comment_parent ) ) {
            return $id;
        }
        
        // self-reference
        if ( $ancestor->comment_parent == $id ) {
            return $id;
        }
        
        // loop
        if ( in_array( $ancestor->comment_parent, $ancestors, true ) ) {
            return $id;
        }
 
        $id          = $ancestor->comment_parent;
        $ancestors[] = $id;
    }
}

Usage in other code with a WP_Comment object:

$root_comment = get_root_comment( $comment_obj->comment_ID );

if ( $root_comment ) {
    // do something with the ID
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x