Contact Form 7: Add Country By IP Shortcode To Email
Copy this code to your theme’s functions.php and use [country_by_ip] shortcode/tag ANYWHERE to print the visitor’s country by his IP address with CF7.
It uses ipinfo.io’s free API, detects the visitor’s IP address and adds CF7 shortcode/tag to use in the email body for example.
Enjoy!
wpcf7_add_shortcode('country_by_ip', 'custom_cf7_country_by_ip', true); function custom_cf7_country_by_ip( $tag='' ) { $ip = $_SERVER['REMOTE_ADDR']; $country = ''; $city = ''; $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json")); if(isset($details->country)) { $country = $details->country; $city = $details->city; }; return ( ($country)?($city.', '.$country):'' ); } add_action( 'wpcf7_init', 'custom_add_form_tag_my_source' ); function custom_add_form_tag_my_source() { wpcf7_add_form_tag( 'country_by_ip', 'custom_cf7_country_by_ip' ); } add_filter( 'wpcf7_special_mail_tags', 'your_special_mail_tag', 10, 3 ); function your_special_mail_tag( $output, $name, $html ) { if ( 'country_by_ip' == $name ) { $output = custom_cf7_country_by_ip(); } return $output; }
Deprecated: wpcf7_add_shortcode is deprecated since Contact Form 7 version 4.6! Use wpcf7_add_form_tag instead.
So better to change wpcf7_add_shortcode on line 1 to wpcf7_add_form_tag. Just did it and it worked! FYI
Hello Zoe
I have try both wpcf7_add_shortcode and wpcf7_add_form_tag but it’s not working.
Please help me
Hey
If still relevant, you can paste your exact code here and I will try to help