How to get store phone number in magento 2
You'll have to use the Magento/Store/Model/Information
class and call the getStoreInformationObject()
method for that.
Recommended way
You'll have to inject this class in your custom block to be able to use that in your template though.
protected $_storeInfo;
public function __construct(
....
\Magento\Store\Model\Information $storeInfo,
....
) {
...
$this->_storeInfo = $storeInfo;
....
}
Then create a custom method to retrieve the phone number:
public function getPhoneNumber()
{
return $this->_storeInfo->getStoreInformationObject(Store $store)->getPhone();
}
Thus in your template you can call:
$block->getPhoneNumber();
Unrecommended way
You should never use the object manager directly (see why here: Magento 2: to use or not to use the ObjectManager directly?)
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeInformation = $objectManager->create('Magento/Store/Model/Information');
$storeInfo = $storeInformation->getStoreInformationObject($store);
Then you can get the phone by calling:
$phone = $storeInfo->getPhone();
you need to inject the an instance of \Magento\Framework\App\Config\ScopeConfigInterface
in your block.
protected $scopeConfig;
public function __construct(
....
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
....
) {
...
$this->scopeConfig = $scopeConfig;
....
}
Then create the method getStorePhone()
public function getStorePhone()
{
return $this->scopeConfig->getValue(
'general/store_information/phone',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
and call in your template echo $block->getStorePhone()
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeInformation = $objectManager->create('Magento\Store\Model\Information');
$store = $objectManager->create('Magento\Store\Model\Store');
$storeInfo = $storeInformation->getStoreInformationObject($store);
$phone = $storeInfo->getPhone();