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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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