解决comment_class或body_class输出暴露注册用户名的问题

如果你的评论列表li标签里面有comment_class的输出可以使用此方法来修正此安全问题。
因为这个class输出会暴露诸如管理员或注册用户的用户名,引起不必要的安全问题。

暴露与非暴露效果如下:

解决comment_class或body_class输出暴露注册用户名的问题-搬砖酱的笔记
解决comment_class或body_class输出暴露注册用户名的问题-搬砖酱的笔记

以下代码加入到主题的functions.php里面


function acgcss_change_comment_or_body_classes($classes, $comment_id){
global $wp_query;
$comment = get_comment( $comment_id );	
$user = get_userdata( $comment->user_id );
$comment_author = 'comment-author-' . sanitize_html_class( $user->user_nicename,$comment->user_id );
$author = $wp_query->get_queried_object();
$archive_author = 'author-' . sanitize_html_class( $author->user_nicename,$author->ID );
foreach( $classes as $key => $class ) {
switch( $class ) {
case $comment_author:
// $classes[$key] = 'comment-author-' . sanitize_html_class( $comment->comment_author, $comment->user_id );
$classes[$key] = 'comment-author-' . sanitize_html_class( $comment->user_id );
break;	
case $archive_author:
// $classes[$key] = 'author-' . sanitize_html_class( get_the_author_meta( 'display_name' ), $author->ID );
$classes[$key] = 'author-' . sanitize_html_class( $author->ID );
break;
}
}	

return $classes;
}
add_filter( 'comment_class', 'acgcss_change_comment_or_body_classes', 10, 4 );
add_filter( 'body_class', 'acgcss_change_comment_or_body_classes', 10, 4 );

注:注释的两行代码为昵称替换,不了解可以不理会。