Using WordPress ‘get_comment’ PHP filter

The get_comment WordPress PHP filter is used to modify or access comment data after it has been retrieved.

Usage

add_filter('get_comment', 'your_custom_function', 10, 1);

function your_custom_function($_comment) {
    // your custom code here
    return $_comment;
}

Parameters

  • $_comment (WP_Comment): The comment data object.

More information

See WordPress Developer Resources: get_comment

Examples

Modify comment author name

Customize the comment author name by appending ‘ (Guest)’ to it.

add_filter('get_comment', 'modify_comment_author_name', 10, 1);

function modify_comment_author_name($_comment) {
    $_comment->comment_author .= ' (Guest)';
    return $_comment;
}

Replace email addresses with ‘[email protected]

Anonymize comment author email addresses by replacing them with a generic email address.

add_filter('get_comment', 'anonymize_comment_author_email', 10, 1);

function anonymize_comment_author_email($_comment) {
    $_comment->comment_author_email = '[email protected]';
    return $_comment;
}

Remove URLs from comment content

Remove all URLs from the comment content to prevent link spamming.

add_filter('get_comment', 'remove_urls_from_comment', 10, 1);

function remove_urls_from_comment($_comment) {
    $_comment->comment_content = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i', '', $_comment->comment_content);
    return $_comment;
}

Remove profanity from comment content

Censor profanities in the comment content by replacing them with asterisks.

add_filter('get_comment', 'remove_profanity_from_comment', 10, 1);

function remove_profanity_from_comment($_comment) {
    $profanities = array('badword1', 'badword2', 'badword3');
    $_comment->comment_content = str_replace($profanities, '****', $_comment->comment_content);
    return $_comment;
}

Add a custom message after each comment

Append a custom message to the comment content.

add_filter('get_comment', 'add_custom_message_to_comment', 10, 1);

function add_custom_message_to_comment($_comment) {
    $custom_message = ' - Thanks for your comment!';
    $_comment->comment_content .= $custom_message;
    return $_comment;
}