WordPress Contact form 7 IP to Location in email

Viewed 704

I am using [_remote_ip] in the email I am reciveng from contact form 7, is there is a way to show the country name or flag instead of the received IP number?

The main issue started when I activated caching, where the php country locate stopped working, so I have to use the [_remote_ip] in the email to know the location of the contact, but it's not a good solution that I always have to locate the ip manually.

That's why I want to check if there is a way to show that IP as a name or as a flag.

1 Answers

This will add a form tag to Contact form 7 [country] - Add this to your functions.php or make it a plugin. TO use this, you'll need a subscription (free tier available) to https://ipstack.com.

add_action('wpcf7_init', function (){
    wpcf7_add_form_tag( 'country' , 'cf7_ip_to_country_form_tag' );
}); 
function cf7_ip_to_country_form_tag($tag){
    // Your API Key for https://ipstack.com is required
    $api_key = 'xxxxxxx';
    // Get API Response
    $url = 'http://api.ipstack.com/' . $_SERVER['REMOTE_ADDR'] . '?access_key=' . $api_key;    
    $response = wp_remote_get($url);
    $body = json_decode(wp_remote_retrieve_body($response));
    
    /* $body = Object returned from ipstack. 
    * $body->country_name = Full Country Name
    * $body->country_code = 2 Letter ISO Abbrev
    * set the value based on what you want.
    */
    
    return '<input type="hidden" name="country" value="'.$body->country_name.'">';
}
Related