你可以适应get_post_acestors()
, 并为注释编写类似的函数。下面是一个返回顶部注释的id或false
. 未测试
function get_root_comment( $comment_id ) {
$comment = get_comment( $comment_id );
if ( ! $comment
|| empty( $comment->comment_parent )
|| $comment->comment_parent == $comment_id
) {
return false;
}
$ancestors = [];
$id = $comment->comment_parent;
$ancestors[] = $id;
while ( $ancestor = get_comment( $id ) ) {
if ( empty ( $ancestor->comment_parent ) ) {
return $id;
}
// self-reference
if ( $ancestor->comment_parent == $id ) {
return $id;
}
// loop
if ( in_array( $ancestor->comment_parent, $ancestors, true ) ) {
return $id;
}
$id = $ancestor->comment_parent;
$ancestors[] = $id;
}
}
在其他代码中使用
WP_Comment
对象:
$root_comment = get_root_comment( $comment_obj->comment_ID );
if ( $root_comment ) {
// do something with the ID
}