How do I get the ID of the top level comment, as in, the top parent comment? Useful functions like get_ancestors()
and get_post_ancestors()
don't work with comments.
2 Answers
Wait? Did you just state get_comment_ancestors()
does not exist? What were they thinking...
We can do this by looping through the entire comment thread until we find the top level comment. We identify it by parent_comment
being set to 0
:
/**
* Return the top parent comment ID
*
* @param $comment_id
* @return comment id
*/
function cc_get_top_level_comment_id_wpse_265978($comment_id){
if (!is_numeric($comment_id)) return;
$parent_comment_id = 1;
// loop comment thread until we find the one which has parent comment ID set to 0
while($parent_comment_id > 0) {
$comment = get_comment($comment_id);
$comment_current_id = $comment->comment_ID;
$parent_comment_id = $comment->comment_parent;
$comment_id = $parent_comment_id;
}
return $comment_current_id;
}
There's a really easy way to do this.
$comment = get_comment($id);
while($comment -> comment_parent != 0) {
$comment = get_comment($comment_parent);
}
This will recursively track back up the ancestor tree until it returns the top level.