1

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 2

1

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;
}
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.