In this post I am going to explain how to get current store information like store id, code, name, url and website id in Magento 2.
1. Using Dependency Injection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | protected $_storeManager; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, array $data = [] ) { $this->_storeManager = $storeManager; parent::__construct($context, $data); } public function getStore() { return $this->_storeManager->getStore(); } public function getStoreId() { return $this->getStore()->getId(); } public function getStoreCode() { return $this->getStore()->getCode(); } public function getStoreName() { return $this->getStore()->getName(); } public function getStoreUrl($fromStore = true) { return $this->getStore()->getCurrentUrl($fromStore); } public function getWebsiteId() { return $this->getStore()->getWebsiteId(); } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //Get Current Store $currentStore = $block->getStore(); echo "<pre>"; print_r($currentStore->getData()); echo "</pre>"; //Get Store Id echo $block->getStoreId() . '<br />'; //Get Store Code echo $block->getStoreCode() . '<br />'; //Get Store Name echo $block->getStoreName() . '<br />'; //Get Store URL echo $block->getStoreUrl() . '<br />'; //Get Websiet Id echo $block->getWebsiteId() . '<br />'; |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); //Get Current Store $currentStore = $storeManager->getStore(); echo "<pre>"; print_r($currentStore->getData()); echo "</pre>"; //Get Store Id echo $currentStore->getStoreId() . '<br />'; //Get Store Code echo $currentStore->getCode() . '<br />'; //Get Store Name echo $currentStore->getName() . '<br />'; //Get Store URL echo $currentStore->getCurrentUrl(true) . '<br />'; //Get Websiet Id echo $currentStore->getWebsiteId() . '<br />'; |
Thats it. Enjoy Magento 2!!
May 6, 2020 at 3:12 pm
Very valuable post and very well explained. Thanks for sharing!
October 14, 2020 at 8:00 pm
The object manager method is exactly what i was looking for to get the store name in my payment method controller
Thanks!