Using WordPress ‘http_origin’ PHP filter

The http_origin WordPress PHP Filter allows you to change the origin of an HTTP request.

Usage

add_filter('http_origin', 'your_function_name');
function your_function_name($origin) {
    // your custom code here
    return $origin;
}

Parameters

  • $origin (string) – The original origin for the request.

More information

See WordPress Developer Resources: http_origin

Examples

Allow requests from a specific domain

To change the origin to allow requests from “example.com“:

add_filter('http_origin', 'allow_specific_origin');
function allow_specific_origin($origin) {
    $allowed_origin = 'https://example.com';
    return $allowed_origin;
}

Allow requests from multiple domains

To allow requests from multiple domains, use an array of allowed origins:

add_filter('http_origin', 'allow_multiple_origins');
function allow_multiple_origins($origin) {
    $allowed_origins = array('https://example.com', 'https://example2.com');

    if (in_array($origin, $allowed_origins)) {
        return $origin;
    }
}

Allow requests from all domains

To allow requests from all domains, return an asterisk (*) as the origin:

add_filter('http_origin', 'allow_all_origins');
function allow_all_origins($origin) {
    return '*';
}

Block requests from a specific domain

To block requests from a specific domain, check if the origin matches the blocked domain and return an empty string if it does:

add_filter('http_origin', 'block_specific_origin');
function block_specific_origin($origin) {
    $blocked_origin = 'https://blocked-example.com';

    if ($origin == $blocked_origin) {
        return '';
    }
    return $origin;
}

Allow requests only from the same domain

To allow requests only from the same domain as your WordPress site, use the get_site_url function to compare the origins:

add_filter('http_origin', 'allow_same_origin');
function allow_same_origin($origin) {
    $site_origin = get_site_url(null, '', 'https');

    if ($origin == $site_origin) {
        return $origin;
    }
}