Security PHP Beginner

Hide Usernames in Comment and Body Classes

Remove the CSS classes that reveal each author's login name in comments and on author archive pages.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 9 lines
// Comments get a class like "comment-author-jane-admin".
add_filter( 'comment_class', function ( array $classes ): array {
	return array_values( array_filter( $classes, fn ( $class ) => ! str_starts_with( $class, 'comment-author-' ) ) );
} );

// Author archives get a class like "author-jane-admin". Keep "author" and "author-{id}".
add_filter( 'body_class', function ( array $classes ): array {
	return array_values( array_filter( $classes, fn ( $class ) => ! preg_match( '/^author-(?!\d+$)/', $class ) ) );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WordPress adds the comment author’s nicename to each comment’s CSS classes, and the author’s nicename to the body class on author pages. Nicenames are often the same as login names, so this publishes usernames in your HTML.

How it works

The comment_class filter removes every class starting with comment-author-. WordPress’s bypostauthor class, which themes use to highlight the post author’s replies, is kept.

The body_class filter removes author-{nicename} from author archives while keeping author and the numeric author-{id} class.

Things to watch

  • Check your theme’s CSS first. If it styles comments by author class, those styles will stop applying.
  • Author archive URLs also contain the nicename. Combine this with the snippets that disable user enumeration or author archives.

How to test it

View the source of a post with comments and search for comment-author-. It shouldn’t appear.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only