How to Build an IP Address Info Plugin for WordPress: A Step-by-Step Guide

Creating plugins for WordPress is always an exciting journey because it allows you to expand your website’s capabilities and add custom features tailored to your specific needs. Today, I’m going to show you how to build an IP Address Info Plugin that fetches information about any IP address and displays it on a dynamic map. Whether you’re curious about where a visitor’s IP is from or you just want to enhance the functionality of your WordPress site, this plugin is a great project for you to tackle. It’s simple yet powerful and relies on two core technologies: Leaflet.js for the map and an IP Geolocation API for fetching the data.

In this guide, we’ll cover everything step-by-step, and by the end, you’ll have a fully functional plugin to showcase on your WordPress website. So, let’s dive in!

What You’ll Need to Build This Plugin

To get started, there are a few things you’ll need:

  1. Basic understanding of PHP and WordPress development – You should be familiar with how WordPress plugins work and be comfortable with writing PHP code.
  2. A running WordPress site – This is where you’ll develop and test your plugin. If you don’t have one yet, you can easily set up WordPress on your local environment or a live server.
  3. A free IP Geolocation API – I’ll show you how to integrate a free IP Geolocation API like ipinfo.io or ipstack.com to fetch details about any IP address.

Step 1: Setting Up Your Plugin

The first step is to create the folder and main file for your plugin. In your WordPress directory, navigate to the wp-content/plugins/ folder and create a new folder for your plugin, for example, ip-address-info-plugin.

Inside this folder, create a new PHP file called ip-address-info.php and open it in your favorite code editor. This file will be the main file for your plugin, where all the magic happens.

Here’s the initial setup for the plugin:

<?php
/**
 * Plugin Name: IP Address Info Plugin
 * Description: A plugin to display IP address information and map using a shortcode.
 * Version: 1.0
 * Author: Asif Khan
 */

With this basic information, WordPress will recognize your plugin. You can now activate it from your WordPress dashboard, but of course, it doesn’t do anything yet. Let’s change that!

Step 2: Enqueuing Scripts and Styles

Before we get to the core functionality, we need to load the necessary libraries, including Leaflet.js, which will help us render the map, and some custom JavaScript to fetch IP information. Leaflet is a powerful open-source JavaScript library that lets you create interactive maps.

To include these files, add the following code inside the ip-address-info.php file:

// Enqueue styles and scripts
function ip_address_info_enqueue_scripts() {
    wp_enqueue_style('leaflet-css', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css');
    wp_enqueue_script('leaflet-js', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', array(), null, true);
    wp_enqueue_script('ip-address-info-js', plugins_url('ip-address-info.js', __FILE__), array('leaflet-js'), null, true);
}
add_action('wp_enqueue_scripts', 'ip_address_info_enqueue_scripts');

Here’s what this code does:

  • wp_enqueue_style loads the Leaflet CSS file, which styles the map.
  • wp_enqueue_script loads the Leaflet JavaScript file and our custom JavaScript file (ip-address-info.js), which we’ll create later to handle fetching the IP information and interacting with the map.

Now that our plugin is starting to take shape, let’s move on to the core part: the shortcode that will display the IP information on the page.

Step 3: Creating the Shortcode

A shortcode is a WordPress feature that allows you to insert dynamic content anywhere on your website, simply by placing a tag (like [ipaddress_info]) in your post or page.

Let’s create a simple shortcode that displays an input field, a button, and placeholders for IP address information and the map. Add the following code inside ip-address-info.php:

// Shortcode function
function ip_address_info_shortcode() {
    ob_start();
    ?>
    <div class="container">
        <h1>IP Address Information</h1>
        <div style="display: flex; flex-wrap: wrap; justify-content: center;">
            <input type="text" id="ip-address" placeholder="Enter IP Address">
            <button id="get-info">Get Information</button>
        </div>
        <div class="loading" id="loading">Loading...</div>
        <div class="error" id="error"></div>
        <div id="info" style="display: none;">
            <h2>Information:</h2>
            <p id="ip">IP: </p>
            <p id="hostname">Hostname: </p>
            <p id="city">City: </p>
            <p id="region">Region: </p>
            <p id="country">Country: </p>
            <p id="latitude">Latitude: </p>
            <p id="longitude">Longitude: </p>
            <p id="org">Organization: </p>
            <p id="loc">Location: <span id="location-link" style="color: #007bff; cursor: pointer; text-decoration: underline;">Show on Map</span></p>
        </div>
        <div id="map" style="height: 300px; width: 100%; margin-top: 20px; display: none;"></div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('ipaddress_info', 'ip_address_info_shortcode');

This shortcode generates a simple UI where users can enter an IP address, click on “Get Information,” and view the fetched data. Additionally, there’s a placeholder for the map, but it’s hidden until the user requests to see the location.

Step 4: Writing JavaScript to Fetch IP Information

Now, let’s create the JavaScript logic that will fetch the IP information and populate the data on the screen. Create a new file called ip-address-info.js in the plugin folder, and add the following code:

document.addEventListener('DOMContentLoaded', () => {
    function initMap(lat, lng) {
        const map = L.map('map').setView([lat, lng], 12);

        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
            maxZoom: 19,
            attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CartoDB</a>'
        }).addTo(map);

        L.marker([lat, lng]).addTo(map);
    }

    document.getElementById('get-info').addEventListener('click', () => {
        const ip = document.getElementById('ip-address').value;
        const infoDiv = document.getElementById('info');
        const loadingDiv = document.getElementById('loading');
        const errorDiv = document.getElementById('error');
        const mapDiv = document.getElementById('map');
        const locationLink = document.getElementById('location-link');
        const button = document.getElementById('get-info');

        if (!ip) {
            errorDiv.textContent = 'Please enter an IP address.';
            errorDiv.style.display = 'block';
            return;
        }

        errorDiv.style.display = 'none';
        loadingDiv.style.display = 'block';
        button.disabled = true;
        button.textContent = 'Loading...';
        mapDiv.style.display = 'none';

        const apiKey = 'replace_with_your_api'; // Replace with your IPinfo API key
        fetch(`https://ipinfo.io/${ip}?token=${apiKey}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok.');
                }
                return response.json();
            })
            .then(data => {
                const [latitude, longitude] = (data.loc || '0,0').split(',').map(Number);
                document.getElementById('ip').textContent = `IP: ${data.ip}`;
                document.getElementById('hostname').textContent = `Hostname: ${data.hostname || 'N/A'}`;
                document.getElementById('city').textContent = `City: ${data.city || 'N/A'}`;
                document.getElementById('region').textContent = `Region: ${data.region || 'N/A'}`;
                document.getElementById('country').textContent = `Country: ${data.country || 'N/A'}`;
                document.getElementById('latitude').textContent = `Latitude: ${latitude}`;
                document.getElementById('longitude').textContent = `Longitude: ${longitude}`;
                document.getElementById('org').textContent = `Organization: ${data.org || 'N/A'}`;
                infoDiv.style.display = 'block';

                locationLink.addEventListener('click', () => {
                    if (latitude && longitude) {
                        mapDiv.style.display = 'block';
                        initMap(latitude, longitude);
                    }
                });
            })
            .catch(error => {
                errorDiv.textContent = `Error fetching IP information: ${error.message}`;
                errorDiv.style.display = 'block';
            })
            .finally(() => {
                loadingDiv.style.display = 'none';
                button.disabled = false;
                button.textContent = 'Get Information';
            });
    });
});

Step 5: Testing and Final Adjustments

You’re now ready to test your plugin. Here’s how:

  1. Upload the Plugin: Upload your plugin folder (`ip-address-info-plugin

) to thewp-content/plugins/` directory of your WordPress site.

  1. Activate the Plugin: Go to the WordPress dashboard, navigate to the Plugins section, and activate your plugin.
  2. Use the Shortcode: Create a new page or post, and add the shortcode [ipaddress_info]. Publish the post and test the functionality.

And that’s it! You now have a working IP Address Info plugin for WordPress.

Live Test : https://apycoder.com/ip-info/

Conclusion

Creating this plugin gives you a hands-on experience with both frontend and backend technologies, including WordPress plugin development, Leaflet.js, and API integration. It’s a practical project that can serve various use cases, from monitoring visitor IPs to educational purposes.

Feel free to extend this plugin further by adding additional features, such as storing IP data or integrating more advanced map features.

If you have any questions or want more customization tips, feel free to reach out in the comments below!

Happy coding!

Leave a Comment

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


Shopping Basket
Scroll to Top