I'm using a third party API service to get a country code from IP address, and to limit the number of requests I'm storing the country code in a local database table, and doing a lookup to that first. If the record doesn't exist, it goes to get the country code and stores it for the next lookup.
However, when looking in the database table, I'm seeing the same IP address and countrycode row that's being added about 20 times.
What's going on? I'm reading through this, and I can't understand why it would do several adds to the table, it makes no sense.
This is causing massive disruption with the API service who are telling us we are abusing their request limit. How can I resolve this?
function get_country_code() {
// Check if site is local dev
if(get_bloginfo('url') == '###') {
global $wpdb;
$ip = $_SERVER['REMOTE_ADDR'];
$access_key = '###';
$record = $wpdb->get_row("SELECT * FROM wp_geoip WHERE ip = '$ip'");
if($record) {
// Return stored country code
return $record->country_code;
} else {
// Make request to ipapi and store country code into table
$ch = curl_init('http://api.ipapi.com/'.$ip.'?access_key='.$access_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$api_result = json_decode($json, true);
$wpdb->insert(
'wp_geoip',
array(
'ip' => $ip,
'country_code' => $api_result['country_code']
),
array(
'%s',
'%s'
)
);
// Return country code
return $api_result['country_code'];
}
} else {
return 'GB';
}
}