How To Get Country name by Country id in Magento 2 / Adobe Commerce

The following below code in your Block of your custom module

Step [1] – Code inside your block / controller / helper file

<?php
/*
 * John_Country

 * @category   Adobe Commerce Region / State List By Country ID
 * @package    Country Name
 * @copyright  Copyright (c) 2023 - Mage2DB.com
 * @Email      johndusa1021@gmail.com
 * @version    1.0.0
 */
namespace John\Country\Model;

use Magento\Directory\Model\Country;
use Magento\Directory\Model\CountryFactory;

class Country
{
/**
* @var Country
*/
public $countryFactory;

public function __construct(
    CountryFactory $countryFactory
) {
    $this->countryFactory = $countryFactory;
}

/**
 * country full name
 *
 * @return string
 */
public function getCountryName($countryId)
{
    $countryName = '';
    $country = $this->countryFactory->create()->loadByCode($countryId);
    if (!empty($country)) {
        $countryName = $country->getName();
    }
    return $countryName;
}

}

Step [2] – if you have written above code in your Custom Block, call this Block in your custom template.

<?php
/*
 * John_Country

 * @category   Adobe Commerce Region / State List By Country ID
 * @package    Country Name
 * @copyright  Copyright (c) 2023 - Mage2DB.com
 * @Email      johndusa1021@gmail.com
 * @version    1.0.0
 */
?>
<?php
 $countryCode="US";

 echo"<BR><B>Country=</b>".$block->getCountryName($countryCode);
?>

Output ::

Leave a Reply

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