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’s free API, detects the visitor’s IP address and adds CF7 shortcode/tag to use in the email body for example.


wpcf7_add_shortcode('country_by_ip', 'custom_cf7_country_by_ip', true);
function custom_cf7_country_by_ip( $tag='' ) {
	$country = '';
	$city = '';
	$details = json_decode(file_get_contents("{$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;

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?