Using WordPress ‘pre_comment_author_name’ PHP filter

The pre_comment_author_name filter allows you to modify the comment author’s name cookie before it is set in WordPress.

Usage

add_filter('pre_comment_author_name', 'your_function_name');
function your_function_name($author_cookie) {
    // Your custom code here
    return $author_cookie;
}

Parameters

  • $author_cookie (string): The comment author name cookie.

More information

See WordPress Developer Resources: pre_comment_author_name

Examples

Uppercase Comment Author Name

This example converts the comment author’s name to uppercase before setting the cookie.

add_filter('pre_comment_author_name', 'uppercase_author_name');
function uppercase_author_name($author_cookie) {
    $author_cookie = strtoupper($author_cookie);
    return $author_cookie;
}

Add Prefix to Comment Author Name

This example adds a “Guest – ” prefix to the comment author’s name.

add_filter('pre_comment_author_name', 'prefix_author_name');
function prefix_author_name($author_cookie) {
    $author_cookie = 'Guest - ' . $author_cookie;
    return $author_cookie;
}

Replace Certain Characters in Comment Author Name

This example replaces any instances of “!” and “@” with an underscore in the comment author’s name.

add_filter('pre_comment_author_name', 'replace_characters_author_name');
function replace_characters_author_name($author_cookie) {
    $author_cookie = str_replace(['!', '@'], '_', $author_cookie);
    return $author_cookie;
}

Limit Comment Author Name Length

This example limits the comment author’s name to a maximum of 20 characters.

add_filter('pre_comment_author_name', 'limit_author_name_length');
function limit_author_name_length($author_cookie) {
    $author_cookie = substr($author_cookie, 0, 20);
    return $author_cookie;
}

Remove Numbers from Comment Author Name

This example removes any numbers from the comment author’s name.

add_filter('pre_comment_author_name', 'remove_numbers_author_name');
function remove_numbers_author_name($author_cookie) {
    $author_cookie = preg_replace('/[0-9]/', '', $author_cookie);
    return $author_cookie;
}