code for showing the geolocation of a visitor on home page

Home » Snippets » code for showing the geolocation of a visitor on home page
0

Created with:

Visibility: 

public

Creator: jai@abrandfantastic.com

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
/**
 * Plugin Name: WP Plugin
 * Description: Show Geolocation on Home Page
 */

function wpturbo_show_geolocation() {
    // Get the visitor's IP address
    $ip_address = $_SERVER['REMOTE_ADDR'];

    // Make a request to the IP geolocation API
    $api_url = "https://api.ipgeolocation.io/ipgeo?apiKey=YOUR_API_KEY&ip={$ip_address}";

    $response = wp_remote_get( $api_url );

    if ( is_wp_error( $response ) ) {
        // Error handling in case the request fails
        $geolocation = __( 'Unable to retrieve geolocation.', 'wpturbo' );
    } else {
        // Parse the JSON response
        $data = json_decode( wp_remote_retrieve_body( $response ) );

        // Extract the relevant information
        $country = $data->country_name;
        $city    = $data->city;
        $lat     = $data->latitude;
        $lng     = $data->longitude;

        // Create the geolocation string
        $geolocation = sprintf( __( 'You are currently in %s, %s (Lat: %s, Lng: %s)', 'wpturbo' ), $city, $country, $lat, $lng );
    }

    // Output the geolocation on the home page
    if ( is_home() || is_front_page() ) {
        echo '<p>' . esc_html( $geolocation ) . '</p>';
    }
}
add_action( 'wp_footer', 'wpturbo_show_geolocation' );
				

Explanation:

This code snippet creates a function called wpturbo_show_geolocation() which is hooked to the wp_footer action. The function retrieves the visitor's IP address from the $_SERVER superglobal and makes a request to an IP geolocation API using the wp_remote_get() function. The API URL includes a placeholder for the IP address, which is replaced with the actual IP address.

If the request to the API is successful, the JSON response is decoded using json_decode() and the relevant information such as country, city, latitude, and longitude is extracted from the response. The geolocation string is then created using sprintf() and stored in the $geolocation variable.

Finally, the geolocation is outputted in a <p> element on the home page using the is_home() and is_front_page() conditional tags to check if the current page is the home page. The esc_html() function is used to escape the geolocation string to prevent any potential security issues.

Register an account to save your snippets or go Pro to get more features.