noptin_locate_ip_address( string $ip_address = '' )
GeoLocates an ip address.
Parameters Parameters
- $ip_address
(string) (Optional) The ip address to located. Default's to the current user's IP Address.
Default value: ''
Return Return
(bool|array)
Source Source
File: includes/functions.php
function noptin_locate_ip_address( $ip_address = '' ) { // Prepare ip address. if ( empty( $ip_address ) ) { $ip_address = noptin_get_user_ip(); } // Ensure that it is valid. if ( empty( $ip_address ) || ! rest_is_ip_address( $ip_address ) ) { return false; } // Try fetching from the cache. $transient_name = md5( "noptin_geolocation_cache_$ip_address" ); if ( get_transient( $transient_name ) ) { return get_transient( $transient_name ); } // Retrieve API key. $api_key = get_noptin_option( 'ipgeolocation_io_api_key' ); if ( empty( $api_key ) ) { return noptin_locate_ip_address_alt( $ip_address ); } // Geolocate the ip. $url = add_query_arg( array( 'apiKey' => $api_key, 'ip' => $ip_address, 'fields' => 'city,continent_name,country_name,state_prov,zipcode,country_flag,currency,time_zone,latitude,longitude,calling_code', ), 'https://api.ipgeolocation.io/ipgeo' ); $response = wp_remote_get( $url ); if ( is_wp_error( $response ) ) { return false; } $geo = json_decode( wp_remote_retrieve_body( $response ), true ); if ( empty( $geo ) ) { log_noptin_message( __( 'Error fetching GeoLocation information.', 'newsletter-optin-box' ) ); return false; } if ( ! empty( $geo['time_zone'] ) ) { $geo['time zone'] = $geo['time_zone']['name'] . ' GMT ' . $geo['time_zone']['offset']; } if ( ! empty( $geo['currency'] ) ) { $geo['currency'] = $geo['currency']['name']; } if ( ! empty( $geo['continent_name'] ) ) { $geo['continent'] = $geo['continent_name']; unset( $geo['continent_name'] ); } if ( ! empty( $geo['country_name'] ) ) { $geo['country'] = $geo['country_name']; unset( $geo['country_name'] ); } if ( ! empty( $geo['state_prov'] ) ) { $geo['state'] = $geo['state_prov']; unset( $geo['state_prov'] ); } $fields = noptin_clean( $geo ); set_transient( $transient_name, $fields, HOUR_IN_SECONDS ); return $fields; }
Expand full source code Collapse full source code View on GitHub
Changelog Changelog
Version | Description |
---|---|
1.2.3 | Introduced. |