WordPress at Your Fingertips

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

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.

There is a function get_post_acestors() for posts in WordPress, but there is no similar function for comments.

Below I have written my function to solve this problem.

/**
 * 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 ){

	if( ! $comm = get_comment( $child_comment ) )
		return null;

	$top_comm = $comm;
	$ancestors = [ $comm->comment_ID ];

	while( $parent_comm = get_comment( $comm->comment_parent ) ){

		$top_comm = $parent_comm;

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

			return $top_comm;
		}

		$ancestors[] = $parent_comm->comment_ID;
		$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] => eonovich@gmail.com
	[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] =>
)
No comments
    Log In