假设您的评论作者是注册用户,最简单的方法可能是使用pre_get_comments action 钩子以修改WP_Comment_Query object\'suser_id 查询变量,以便查询仅返回来自当前用户的注释:
function wpse262203_restrict_comment_views( $comments_query ) {
// Don\'t interfere with comment results in the dashboard
if( is_admin() )
return;
$current_user = wp_get_current_user(); // Get the current user
if( $current_user instanceof WP_User && is_user_logged_in() ) {
// The visitor is logged in as a WordPress user...
// If they\'re an administrator, don\'t filter the comments
if( in_array( \'administrator\', $current_user->roles ) )
return;
// Otherwise, restrict queried comments to those authored by this user.
$comments_query->query_vars[ \'user_id\' ] = $current_user->ID;
}
else {
// The visitor isn\'t logged in - make sure no comments are queried.
$comments_query->query_vars[ \'comment__in\' ] = array(0);
}
}
add_action( \'pre_get_comments\', \'wpse262203_restrict_comment_views\' );
您还可以
use current_user_can() instead of/in addition to checking for user roles 定制筛选评论的对象。
而您也可以通过使用wp_get_current_commenter() 与author_email WP_Comment_Query 这不是非常可靠或安全的。匿名评论者ID数据存储在Cookie中,这意味着用户可以清除它,否则Cookie可能会过期-在这种情况下,用户将无法查看他们的评论,直到他们发布另一条评论。凭证也很容易被欺骗——狡猾的访问者可能会获得其他用户的评论。
编辑-为什么这不起作用,之前经过进一步调查,我之前尝试使用WP_Comment_Query::set() 更改查询变量失败,因为事实证明,WP_Comment_Query 实际上没有set() 方法,而不是WP_Query 副本(参见ticket #39120). 但它确实有__call() "Magic Method", 正在拦截对不存在的set() 方法并返回false,从而防止了PHP通常会抛出的错误,并使我困惑不已。