-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip-to-county-for-cf7.php
More file actions
48 lines (40 loc) · 1.67 KB
/
ip-to-county-for-cf7.php
File metadata and controls
48 lines (40 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/**
* Plugin Name: CF7 Country Detector
* Plugin URI: https://github.com/builderhall/CF7-Country-Detector
* Description: Captures user IP location when a Contact Form 7 form is submitted.
* Version: 1.1
* License: GPLv3 or later
* Author: Builder Hall Ltd.
* Author URI: https://builderhall.com
*/
// Hook into Contact Form 7 form submission
add_action('wpcf7_before_send_mail', 'capture_user_ip_location');
function capture_user_ip_location($contact_form) {
// Get the Contact Form 7 submission instance
$submission = WPCF7_Submission::get_instance();
// If submission exists, proceed
if ($submission) {
// Get user's IP address
$user_ip = '';
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_array = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$user_ip = trim($ip_array[0]);
} else {
$user_ip = $_SERVER['REMOTE_ADDR'];
}
// Get user's IP location using
$ip_info = json_decode(file_get_contents("https://ipinfo.io/{$user_ip}/json"));
// Extract relevant location information if available
if ($ip_info && isset($ip_info->city, $ip_info->region, $ip_info->country)) {
$location = "{$ip_info->city}, {$ip_info->region}, {$ip_info->country}";
} else {
$location = 'Location data not available';
}
// Add the location to the Contact Form 7 email body
$mail = $contact_form->prop('mail');
$mail['body'] .= "\nUser Location: {$location}";
// Update the mail properties
$contact_form->set_properties(array('mail' => $mail));
}
}