我正在使用Buddypress创建教室,只有给定班级的成员才能看到并回应同学的评论。我通过过滤实现了这一点pre_get_comments
, 正在查询user_id
类成员的。
然而,讲师可能是多个班级的成员,因此我还需要过滤掉他们对未登录学生班级的学生的评论的回复。
我想出了以下解决方案:
function filter_the_comments( $array ) {
$comment_IDs = array();
foreach ( $array as $key => $val ) {
array_push($comment_IDs, $val->comment_ID);
}
foreach ( $array as $key => $val ) {
if ( !in_array( $val->comment_parent, $comment_IDs ) && $val->comment_parent != 0 )
unset( $array[ $key ] );
}
return $array;
};
add_filter( \'the_comments\', \'filter_the_comments\', 10, 1 );
这是可行的,但作为一个更像是鞋匠而不是程序员的人,我担心这可能效率低下,我想知道是否有更好的方法来实现同样的结果。
谢谢
最合适的回答,由SO网友:inarilo 整理而成
一些建议,作为评论添加:
function filter_the_comments( $array ) {
$comment_IDs = array();
foreach ( $array as $key => $val ) {
//assuming the comments are sorted by date in ascending order, a parent has to come before the child comment, so there is no need to wait till all subsequent IDs have been added in order to check for this comment\'s parent
//the && operator stops executing as soon as a condition fails, so it\'s more efficient to check if there is a parent first
//0 evaluates to false and other values to true, so the comparison can be skipped
if ($val->comment_parent && !in_array( $val->comment_parent, $comment_IDs )) unset( $array[ $key ] );
//there is no need to add this comment\'s ID if you have removed it, so put this in the else statement
else array_push($comment_IDs, $val->comment_ID);
}
return $array;
};