Last updated on October 18, 2023

WP Forms user location tracking

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Capture and track user locations in forms.

To track the user’s location in WP Forms, you can use a combination of JavaScript and PHP code. The JavaScript code will retrieve the user’s location using the browser’s geolocation API, and then send the location data to the server using an AJAX request. The PHP code will handle the AJAX request and store the location data in the WordPress database.

Here’s an example of how you can achieve this functionality:

  1. First, enqueue the JavaScript code in your theme’s functions.php file or in a custom plugin:
function wpsnippets_enqueue_scripts() {
    wp_enqueue_script( 'wpsnippets-location-tracking', get_template_directory_uri() . '/js/location-tracking.js', array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_enqueue_scripts' );
  1. Create a new JavaScript file called location-tracking.js in your theme’s
    directory (create one if it doesn’t exist) and add the following code:
jQuery(document).ready(function($) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            // Send the location data to the server using AJAX
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'wpsnippets_save_location',
                    latitude: latitude,
                    longitude: longitude
                },
                success: function(response) {
                    console.log('Location data saved successfully.');
                }
            });
        });
    }
});
  1. Now, handle the AJAX request in your theme’s functions.php file or in a custom plugin:
function wpsnippets_save_location() {
    if (isset($_POST['latitude']) && isset($_POST['longitude'])) {
        $latitude = sanitize_text_field($_POST['latitude']);
        $longitude = sanitize_text_field($_POST['longitude']);

        // Save the location data in the WordPress database
        update_user_meta(get_current_user_id(), 'wpsnippets_latitude', $latitude);
        update_user_meta(get_current_user_id(), 'wpsnippets_longitude', $longitude);

        wp_send_json_success();
    } else {
        wp_send_json_error('Location data not found.');
    }
}
add_action( 'wp_ajax_wpsnippets_save_location', 'wpsnippets_save_location' );
add_action( 'wp_ajax_nopriv_wpsnippets_save_location', 'wpsnippets_save_location' );

This code registers an AJAX action called wpsnippets_save_location that handles the location data sent from the JavaScript code. It retrieves the latitude and longitude values from the AJAX request, sanitizes them, and then saves them as user meta using the update_user_meta function. Finally, it sends a JSON response back to the JavaScript code to indicate whether the location data was saved successfully or not.

By implementing this code, you will be able to track the user’s location in WP Forms and store it in the WordPress database for further use or analysis.

Examples

Example 1: Tracking User Location on WP Forms Submission

This use case demonstrates how to track the user’s location when they submit a form created with WP Forms plugin.

function wpsnippets_track_user_location( $fields, $entry, $form ) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = file_get_contents( 'http://ip-api.com/json/' . $ip_address );
    $location_data = json_decode( $location );

    $fields['user_location'] = $location_data->city . ', ' . $location_data->country;

    return $fields;
}
add_filter( 'wpforms_process_entry_fields', 'wpsnippets_track_user_location', 10, 3 );

This code example adds a filter to the wpforms_process_entry_fields hook, which allows us to modify the form fields before they are saved. Inside the callback function, we retrieve the user’s IP address using $_SERVER['REMOTE_ADDR']. Then, we use the IP address to fetch the user’s location data from the IP-API service. The location data is then added to the form fields array with the key user_location.

Example 2: Storing User Location in a Custom Field

This use case demonstrates how to store the user’s location in a custom field in the WordPress database.

function wpsnippets_store_user_location( $fields, $entry, $form ) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = file_get_contents( 'http://ip-api.com/json/' . $ip_address );
    $location_data = json_decode( $location );

    update_post_meta( $entry['post_id'], 'user_location', $location_data->city . ', ' . $location_data->country );

    return $fields;
}
add_filter( 'wpforms_process_entry_fields', 'wpsnippets_store_user_location', 10, 3 );

In this code example, we use the same approach as in Example 1 to retrieve the user’s location data. However, instead of adding it to the form fields array, we use the update_post_meta function to store the location in a custom field named user_location associated with the form entry’s post ID.

Example 3: Sending User Location in Email Notifications

This use case demonstrates how to include the user’s location in email notifications sent by WP Forms.

function wpsnippets_include_user_location_in_email( $fields, $entry, $form_data ) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $location = file_get_contents( 'http://ip-api.com/json/' . $ip_address );
    $location_data = json_decode( $location );

    $fields['user_location'] = $location_data->city . ', ' . $location_data->country;

    return $fields;
}
add_filter( 'wpforms_email_fields', 'wpsnippets_include_user_location_in_email', 10, 3 );

This code example adds a filter to the wpforms_email_fields hook, which allows us to modify the fields included in email notifications. Inside the callback function, we retrieve the user’s location data using the same method as in the previous examples. Then, we add the location data to the email fields array with the key user_location. This will ensure that the user’s location is included in the email notifications sent by WP Forms.

Last updated on October 18, 2023. Originally posted on December 24, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *