Getting All Available Currencies in Magento: A Developer’s Guide
As a newcomer to Magento development, you’re likely wondering how to fetch all available currencies for a given website or store. This blog post will guide you through this process step-by-step.
Understanding Magento’s Currency Management
Magento manages currencies at both the global and per-store level. By default, it includes USD and EUR currencies in the global scope. When you create new websites or stores, you can enable additional currencies for each one separately.
Fetching Currencies by Website ID
If you have a website ID, you can retrieve all enabled currencies using Magento’s core_currency database table.
// Assuming you already have a database connection
$websiteId = 1;
$query = "SELECT code FROM core_currency WHERE website_id = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$websiteId]);
$currencies = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($currencies as $currency) {
echo $currency . "\n";
}
This script retrieves the currency codes (e.g., USD, EUR) for the specified website ID. Remember to replace 1 with your actual website ID.
Fetching Currencies by Store ID
For a specific store, you can use Magento’s API or repository pattern to fetch enabled currencies.
- Using the Currency Repository:
// Assuming you have a Magento application object
$currencyRepository = $this->getObjectManager()->create('Magento\Directory\Model\CurrencyFactory');
$currencies = $currencyRepository->create()->getCollection()
->addStoreFilter($storeId)
->load();
foreach ($currencies as $currency) {
echo $currency->getCode() . "\n";
}
This code uses the CurrencyFactory to create a new currency collection. The addStoreFilter($storeId) method ensures only currencies enabled for the specified store are returned.
- Using the Currency API:
You can also use Magento’s Currency API endpoints, which are more lightweight and recommended for production environments:
$url = 'http://your-magento-url/rest/V1/directory/currency/allowed?website_id=1&store_id=2';
$response = file_get_contents($url);
if ($response !== false) {
$currencies = json_decode($response, true);
print_r($currencies); // Prints the array of allowed currency codes
}
Replace 'http://your-magento-url/rest/V1/directory/currency/allowed?website_id=1&store_id=2' with your actual Magento URL and desired website and store IDs.
Conclusion
Fetching available currencies in Magento is a straightforward process once you understand the data structure. Whether you’re working with database queries or using Magento’s built-in APIs, retrieving currency information is an essential task when developing bespoke features for e-commerce platforms.
Remember to check out our comprehensive guide on Magento API: A Developer’s Reference for more in-depth insights into Magento’s API endpoints and best practices.