WordPress at Your Fingertips

How to Get WP Top Level Comment

WordPress don 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, but there is no such a function for comments.

Let's fix this situation by writing our own function which will get top comment of the specified comment.

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

	$comm = get_comment( $child_comment );
	$top_comm = $comm;
	$parent_comm = $comm->comment_parent ? get_comment( $comm->comment_parent ) : false;

	if( ! $parent_comm )
		return $top_comm;

	while( $parent_comm ){

		$_comm = get_comment( $parent_comm );

		// top found
		if( ! $_comm->comment_parent ){
			$top_comm = $_comm;
			break;
		}

		$parent_comm = get_comment( $_comm->comment_parent );

		// this can't be
		if( $_comm->comment_parent === $parent_comm->comment_parent )
			return null;
	}

	return $top_comm;
}

Now imagine that we haw comment tree with such IDs:

  • Comment with ID 1
    • Child Comment with ID 2
      • Child Comment with ID 3

Now if we pass the ID 3 to our function, we get 1 comment as WP_Comment instance:

$top_comment = get_top_comment( 3 );

print_r( $top_comment );

/*
WP_Comment Object
(
	[comment_ID] => 1
	[comment_post_ID] => 272
	[comment_author] => mitesh
	[comment_author_email] => mish.p.lr@gmail.com
	[comment_author_url] =>
	[comment_author_IP] => 123.201.108.140
	[comment_date] => 2021-06-30 10:01:13
	[comment_date_gmt] => 2021-06-30 13:01:13
	[comment_content] => I have question : how many distinct secret key can be generated by wp_generate_password?
	[comment_karma] => 0
	[comment_approved] => 1
	[comment_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
	[comment_type] => comment
	[comment_parent] => 0
	[user_id] => 0
	[children:protected] =>
	[populated_children:protected] =>

)
*/
No comments
    Log In