Using WordPress ‘pre_comment_user_agent’ PHP filter

pre_comment_user_agent is a WordPress PHP filter that allows you to modify the comment author’s browser user agent before it is saved in the database.

Usage

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

function your_custom_function($comment_agent) {
    // Your custom code here
    return $comment_agent;
}

Parameters

  • $comment_agent (string): The comment author’s browser user agent.

More information

See WordPress Developer Resources: pre_comment_user_agent

Examples

Anonymize User Agent

Remove specific information from the user agent to protect the commenter’s privacy.

add_filter('pre_comment_user_agent', 'anonymize_user_agent', 10, 1);

function anonymize_user_agent($comment_agent) {
    $anonymized_agent = preg_replace('/\s\(.+?\)/', '', $comment_agent);
    return $anonymized_agent;
}

Replace User Agent with Custom String

Replace the user agent with a custom string for all comments.

add_filter('pre_comment_user_agent', 'replace_with_custom_string', 10, 1);

function replace_with_custom_string($comment_agent) {
    return 'Custom User Agent';
}

Remove User Agent for Specific Comments

Remove the user agent for comments containing a specific keyword.

add_filter('pre_comment_user_agent', 'remove_agent_for_specific_comments', 10, 2);

function remove_agent_for_specific_comments($comment_agent, $commentdata) {
    if (strpos($commentdata['comment_content'], 'keyword') !== false) {
        return '';
    }
    return $comment_agent;
}

Add Custom Information to User Agent

Add custom information to the user agent string.

add_filter('pre_comment_user_agent', 'add_custom_information', 10, 1);

function add_custom_information($comment_agent) {
    return $comment_agent . ' [Custom Info]';
}

Filter User Agent Based on Length

Remove user agent information for comments with user agents longer than a specified length.

add_filter('pre_comment_user_agent', 'filter_based_on_length', 10, 1);
function filter_based_on_length($comment_agent) {
if (strlen($comment_agent) > 100) {
return '';
}
return $comment_agent;
}