How to get top (root) level comment by any child comment

WordPress don't have a function to retrieve top level comment for the specified comment. To do that for posts or taxonomies we have get_ancestors() and get_post_ancestors() functions.

How can we check if the current WordPress comment is the top comment in the comment branch. If the current comment is not the root comment, then we need to find the root (top level) comment in the comment tree.

That is, we need a function that gets the top comment in the comment branch no matter what comment of the tree we pass into it.

Below I have written my function to solve this problem and get top parent comment of the specified one.

/**
 * Retrieves top level comment of specified comment.
 *
 * @param int|WP_Comment $child_comment
 *
 * @return WP_Comment|null Null on error.
 */
function get_top_comment( $child_comment ){

	$top_comm = get_comment( $child_comment );
	if( ! $top_comm ){
		return null;
	}

	$ancestors = [ $top_comm->comment_ID ];

	while( $top_comm->comment_parent ){

		$parent_comm = get_comment( $top_comm->comment_parent );
		if( ! $parent_comm ){
			return $top_comm;
		}

		// infinite loop
		if( in_array( $parent_comm->comment_ID, $ancestors, true ) ){
			trigger_error( "Comment $parent_comm->comment_ID breaks comment tree." );

			return null;
		}

		$ancestors[] = $parent_comm->comment_ID;
		$top_comm = $parent_comm;
	}

	return $top_comm;
}
Example of usage

Suppose we have this branch of comments (comment IDs are given):

  • 10
    • 20
      • 30

Now if we pass any of these IDs to the get_top_comment() function in response we get WP_Comment object of comment 10:

$top_comment = get_top_comment( 30 );
$top_comment = get_top_comment( 20 );
$top_comment = get_top_comment( 10 );

Any of this lines retrieves such object:

WP_Comment Object
(
	[comment_ID] => 10
	[comment_post_ID] => 95
	[comment_author] => Johnny
	[comment_author_email] => [email protected]
	[comment_author_url] =>
	[comment_author_IP] => 162.210.194.38
	[comment_date] => 2020-11-12 11:27:59
	[comment_date_gmt] => 2020-11-12 06:27:59
	[comment_content] => Comment text
	[comment_karma] => 0
	[comment_approved] => 1
	[comment_agent] => Mozilla/5.0 (Windows NT 6.3; Win64; x64)
	[comment_type] => comment
	[comment_parent] => 0
	[user_id] => 0
	[children:protected] =>
	[populated_children:protected] =>
)