WC_Geolocation::geolocate_via_api()
Use APIs to Geolocate the user.
Geolocation APIs can be added through the use of the woocommerce_geolocation_geoip_apis filter. Provide a name=>value pair for service-slug=>endpoint.
If APIs are defined, one will be chosen at random to fulfil the request. After completing, the result will be cached in a transient.
Метод класса: WC_Geolocation{}
Хуки из метода
Возвращает
Строку
.
Использование
$result = WC_Geolocation::geolocate_via_api( $ip_address );
- $ip_address(строка) (обязательный)
- IP address.
Код WC_Geolocation::geolocate_via_api() WC Geolocation::geolocate via api WC 9.2.3
private static function geolocate_via_api( $ip_address ) { $country_code = get_transient( 'geoip_' . $ip_address ); if ( false === $country_code ) { $geoip_services = apply_filters( 'woocommerce_geolocation_geoip_apis', self::$geoip_apis ); if ( empty( $geoip_services ) ) { return ''; } $geoip_services_keys = array_keys( $geoip_services ); shuffle( $geoip_services_keys ); foreach ( $geoip_services_keys as $service_name ) { $service_endpoint = $geoip_services[ $service_name ]; $response = wp_safe_remote_get( sprintf( $service_endpoint, $ip_address ), array( 'timeout' => 2, 'user-agent' => 'WooCommerce/' . wc()->version, ) ); if ( ! is_wp_error( $response ) && $response['body'] ) { switch ( $service_name ) { case 'ipinfo.io': $data = json_decode( $response['body'] ); $country_code = isset( $data->country ) ? $data->country : ''; break; case 'ip-api.com': $data = json_decode( $response['body'] ); $country_code = isset( $data->countryCode ) ? $data->countryCode : ''; // @codingStandardsIgnoreLine break; default: $country_code = apply_filters( 'woocommerce_geolocation_geoip_response_' . $service_name, '', $response['body'] ); break; } $country_code = sanitize_text_field( strtoupper( $country_code ) ); if ( $country_code ) { break; } } } set_transient( 'geoip_' . $ip_address, $country_code, DAY_IN_SECONDS ); } return $country_code; }