Posted on

Magento2.4 Set default country as per ip address in shipping address

I need to set country id as per guest Ip address in shipping address on checkout page.
Override LayoutProcessor and add code but its not working.

di.xml

<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”>
<type name=”MagentoCheckoutBlockCheckoutLayoutProcessor”>
<plugin name=”city_country_disable” type=”VendorModulePluginCheckoutModelCheckoutLayoutProcessor” sortOrder=”100″/>
</type>
</config>

LayoutProcessor.php

class LayoutProcessor{
public function afterProcess(MagentoCheckoutBlockCheckoutLayoutProcessor $subject,array $jsLayout){
$selectedCountry = ‘UK’; //Country Coming From Ipaddress/session
$jsLayout[‘components’][‘checkout’][‘children’][‘steps’][‘children’][‘shipping-step’][‘children’]
[‘shippingAddress’][‘children’][‘shipping-address-fieldset’][‘children’][‘country_id’][‘value’] = $selectedCountry;
return $jsLayout;
}
}

selected country show in app/design/frontend/vendor/theme/Magento_Checkout/view/frontend/templates/onepage.phtml
On below script

<script type=”text/x-magento-init”>
{
“#checkout”: {
“Magento_Ui/js/core/app”: <?= /* @noEscape */ $block->getJsLayout() ?>
}
}
</script>

but in shipping address, always default country selected, which set in backend.

Leave a Reply

Your email address will not be published.