Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barryhughes/38cb7dd9a48863fd06f669dbd36cc4f2 to your computer and use it in GitHub Desktop.
Save barryhughes/38cb7dd9a48863fd06f669dbd36cc4f2 to your computer and use it in GitHub Desktop.
<?php
/**
* Facilitates dictating a separate (IP-address protected) Google Maps
* API key for server-side geocoding requests.
*/
class Server_Side_Google_Maps_Key {
/**
* @var string
*/
private $key = '';
/**
* Sets up a Google Maps API key to be used for server-side initiated
* geocoding requests.
*
* @param string $key
*/
public function __construct( string $key ) {
$this->key = $key;
add_filter( 'pre_http_request', [ $this, 'pre_http_request' ], 10, 3 );
}
/**
* @param mixed $response
* @param array $args
* @param string $url
*
* @return array|WP_Error
*/
public function pre_http_request( $response, $args, $url ) {
// If this is not a Google Maps geocoding request, or if it is but our replacement
// key is already in place, then we need do nothing more.
if (
0 !== strpos( $url, 'https://maps.googleapis.com/maps/api/geocode' )
|| false !== strpos( $url, $this->key )
) {
return $response;
}
// Replace the API key.
$url = add_query_arg( 'key', $this->key, $url );
// Perform a new request with our alternative API key and return the result.
return wp_remote_get( $url, $args );
}
}
// Specify our alternative API key here (to be used for server-side geocoding requests).
new Server_Side_Google_Maps_Key( 'IP_ADDRESS_PROTECTED_API_KEY' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment