Using WordPress ‘http_headers_useragent’ PHP filter

The http_headers_useragent WordPress PHP Filter allows you to modify the user agent value sent with an HTTP request.

Usage

add_filter('http_headers_useragent', 'modify_user_agent', 10, 2);
function modify_user_agent($user_agent, $url) {
    // your custom code here
    return $user_agent;
}

Parameters

  • $user_agent (string) – The original WordPress user agent string.
  • $url (string) – The request URL.

More information

See WordPress Developer Resources: http_headers_useragent

Examples

Change User Agent for All Requests

Modify the user agent for all HTTP requests made by WordPress.

add_filter('http_headers_useragent', 'change_all_user_agent', 10, 2);
function change_all_user_agent($user_agent, $url) {
    $user_agent = 'My Custom User Agent';
    return $user_agent;
}

Change User Agent for Specific Domain

Modify the user agent only for requests to a specific domain.

add_filter('http_headers_useragent', 'change_specific_domain_user_agent', 10, 2);
function change_specific_domain_user_agent($user_agent, $url) {
    if (strpos($url, 'example.com') !== false) {
        $user_agent = 'Custom User Agent for Example Domain';
    }
    return $user_agent;
}

Change User Agent Based on Request URL Pattern

Modify the user agent for requests with a specific URL pattern.

add_filter('http_headers_useragent', 'change_url_pattern_user_agent', 10, 2);
function change_url_pattern_user_agent($user_agent, $url) {
    if (preg_match('/\/api\//', $url)) {
        $user_agent = 'Custom User Agent for API Endpoints';
    }
    return $user_agent;
}

Append Additional Information to User Agent

Add extra information to the user agent string.

add_filter('http_headers_useragent', 'append_info_to_user_agent', 10, 2);
function append_info_to_user_agent($user_agent, $url) {
    $user_agent .= '; Custom Info';
    return $user_agent;
}

Remove WordPress Version from User Agent

Remove the WordPress version from the user agent string.

add_filter('http_headers_useragent', 'remove_wp_version_from_user_agent', 10, 2);
function remove_wp_version_from_user_agent($user_agent, $url) {
    $user_agent = preg_replace('/WordPress\/\d+\.\d+(\.\d+)?;/', '', $user_agent);
    return $user_agent;
}