Created
February 24, 2020 23:04
-
-
Save barryhughes/38cb7dd9a48863fd06f669dbd36cc4f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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