Skip to content

Instantly share code, notes, and snippets.

@kpirnie
Created August 13, 2025 18:15
Show Gist options
  • Save kpirnie/21b9dc37963ab118fb3b38010241892b to your computer and use it in GitHub Desktop.
Save kpirnie/21b9dc37963ab118fb3b38010241892b to your computer and use it in GitHub Desktop.
WordPress - Add Basic Auth to Remote Requests
/**
* function to filter the remote request arguments to ensure we are passing
* http auth headers when remotely calling from staging or dev environments
* only used if HOST of requested URL matches the site's home HOST and if the auth
* exists
*
* @param array $_the_args The existing arguments passed with the request.
* @param string $_the_url The URL being requested.
*
*/
if( ! function_exists( 'remote_auth_filter' ) ) {
function remote_auth_filter( $_the_args, $_the_url ) {
// parse the passed URL
$_url = wp_parse_url( $_the_url, PHP_URL_HOST );
// now get the site's home url and parse it for the host as well
$_home = wp_parse_url( get_site_url( ), PHP_URL_HOST );
// we only want to do this if the url requested, and the site hom url match
if( $_url === $_home ) {
// check if we have basic auth
if( isset( $_SERVER["HTTP_AUTHORIZATION"] ) ) {
// add it to our arguments as it is
$_the_args['headers']['Authorization'] = $_SERVER["HTTP_AUTHORIZATION"];
}
}
// return them
return $_the_args;
}
}
// now hook into the proper filter
add_filter( 'http_request_args', 'remote_auth_filter', PHP_INT_MAX, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment