In Magento 2 customer IP is generally getting displayed at the admin order page, But not the customer location.
So today we are going to talk about displaying customer location on the admin order page by using a location API.
Follow the below tutorial step wise to get it done:
1. Create {{Your Vendor name}}/{{Extension Name}}/registration.php
For Example : Magemonkey/CustomerLocation/registration.php
<?php MagentoFrameworkComponentComponentRegistrar::register( MagentoFrameworkComponentComponentRegistrar::MODULE, 'Magemonkey_CustomerLocation', __DIR__ );
2. Create {{Your Vendor name}}/{{Extension Name}}/composer.json
For Example : Magemonkey/CustomerLocation/composer.json
{ "name": "magemonkey/customerlocation", "version": "1.0.0", "description": "Display Customer Location on admin order page", "type": "magento2-module", "license": [ "OSL-3.0", "AFL-3.0" ], "autoload": {"files": ["registration.php"], "psr-4": {"Magemonkey\CustomerLocation\": ""}}, "keywords": [ "eCommerce" ,"freegeoip.net" ,"Geolocation" ,"Magento" ,"Magento 2" ,"Magento extension" ] }
3. Create {{Your Vendor name}}/{{Extension Name}}/etc/module.xml
For Example : Magemonkey/CustomerLocation/etc/module.xml
<?xml version='1.0'?> <configxmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework:Module/etc/module.xsd'> <module name='Magemonkey_CustomerLocation' setup_version='1.0.0'/> </config>
4. Create {{Your Vendor name}}/{{Extension Name}}/view/adminhtml/layout/sales_order_view.xml
For Example : Magemonkey/CustomerLocation/view/adminhtml/layout/sales_order_view.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head><script src='Magemonkey_CustomerLocation::general.js' defer='defer'/></head> </page>
5. Create {{Your Vendor name}}/{{Extension Name}}/view/adminhtml/web/general.js
For Example : Magemonkey/CustomerLocation/view/adminhtml/web/general.js
require([ 'jquery' ], function($) {$(function() { var $ipAddressCell = $('.order-information-table td').filter(function() { return /d+.d+.d+.d+/.test(this.innerHTML); }); if ($ipAddressCell.length) { var address = $ipAddressCell.html(); if ('127.0.0.1' !== address) { $.get('https://freegeoip.app/json/' + address, function(data) { var location = [data['country_name'], data['region_name'], data['city']] .filter(function(item) {return !!item;}) .join(', ') ; var $ipAddressRow = $ipAddressCell.closest('tr'); var $geoRow = $('<tr>') .append($('<th>').append($.mage.__('Customer Location'))) .append($('<td>').append(location)) ; $ipAddressRow.after($geoRow); }); } } }); });
After follow above steps run below commands:
- php bin/magento setup:upgrade - php bin/magento cache:flush
Once you’ll execute above steps, you’ll able to see the location at the admin order view page as shown below: