Magento, Magento 2

How to Switch Currency Programmatically in Magento 2

How to Switch Currency Programmatically in Magento 2

In this tutorial, Today I will explain to how to switch currency programmatically in Magento 2. When you develop custom module, sometimes you need to change current currency programmatically. At that time, how to change programmatically instead of switch currency from currency switcher?

Steps of Switch Currency Programmatically in Magento 2 :

You may also like this :

1. Object Manager Method :


/**
 * Created By : Rohan Hapani
 */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);
$currency = "INR"; // set currency code which you want to set
if ($currency) {
   $storeManager->getStore()->setCurrentCurrencyCode($currency);
}

You can use this above code in your PHTML, controller or block.

2. Dependency Injection Method :


/**
 * Created By : Rohan Hapani
 */

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @param  \Magento\Store\Model\StoreManagerInterface $storeManager
 */
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager
){
    $this->storeManager = $storeManager;
}

/**
 * Switch Currency Programmatically
 */
public function changeStoreCurrency()
{
    $currency = "INR"; // set currency code which you want to set
    if ($currency) {
        $this->storeManager->getStore()->setCurrentCurrencyCode($currency);
    }
}

You can add this above code in block, model and controller. If you will add this code in controller and execute that controller at frontend then, currency will set INR of the current store.

I do not recommended to use object manager method. Always use dependency injection method.

That’s it !!!

Using this way, You can change current store currency without currency switcher.

I hope this blog is easy to understand about how to switch/change currency programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,