2

I need to programmatically get the country, zip code and state of the store that is at:

Stores->Configuration->SALES->Shipping Settings->Origin enter image description here

1 Answer 1

1

Here are the code to get country, region and zip code

<?php

use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;

class MyClass
{
    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var CountryFactory
     */
    protected $countryFactory;

    /**
     * @var RegionFactory
     */
    protected $regionFactory;

    /**
     * MyClass constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param CountryFactory $countryFactory
     * @param RegionFactory $regionFactory
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        CountryFactory $countryFactory,
        RegionFactory $regionFactory
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->countryFactory = $countryFactory;
        $this->regionFactory = $regionFactory;
    }

    /**
     * Get shipping country name
     * @return string
     */
    public function getShippingCountry()
    {
        $countryCode = $this->scopeConfig->getValue(
            'shipping/origin/country_id',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $country = $this->countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

    /**
     * Get shipping region name
     * @return string
     */
    public function getShippingRegion()
    {
        $regionId = $this->scopeConfig->getValue(
            'shipping/origin/region_id',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $region = $this->regionFactory->create()->load($regionId);
        return $region->getName();
    }

    /**
     * Get shipping postcode
     * @return string
     */
    public function getShippingPostcode()
    {
        return $this->scopeConfig->getValue(
            'shipping/origin/postcode',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.