Magento 2: Get Store Information (Store ID, Code, Name, URL, Website ID)

This article shows how we can get store information in Magento 2. We will be fetching store id, store code, store name, store url, and store’s website id. We also write a function which checks if the store is active or not.

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of StoreManagerInterface in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php


<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{	
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,		
		array $data = []
	)
	{			
		parent::__construct($context, $data);
	}
	
	/**
     * Get store identifier
     *
     * @return  int
     */
	public function getStoreId()
	{
		return $this->_storeManager->getStore()->getId();
	}
	
	/**
     * Get website identifier
     *
     * @return string|int|null
     */
	public function getWebsiteId()
	{
		return $this->_storeManager->getStore()->getWebsiteId();
	}
	
	/**
     * Get Store code
     *
     * @return string
     */
	public function getStoreCode()
	{
		return $this->_storeManager->getStore()->getCode();
	}
	
	/**
     * Get Store name
     *
     * @return string
     */
	public function getStoreName()
	{
		return $this->_storeManager->getStore()->getName();
	}
	
	/**
     * Get current url for store
     *
     * @param bool|string $fromStore Include/Exclude from_store parameter from URL
     * @return string     
     */
	public function getStoreUrl($fromStore = true)
	{
		return $this->_storeManager->getStore()->getCurrentUrl($fromStore);
	}
	
	/**
     * Check if store is active
     *
     * @return boolean
     */
	public function isStoreActive()
	{
		return $this->_storeManager->getStore()->isActive();
	}
}
?>

See more functions in vendor/magento/module-store/Model/Store.php.

Now, we print the store information in our template (.phtml) file.


echo $block->getStoreId() . '<br />';
echo $block->getStoreCode() . '<br />';
echo $block->getWebsiteId() . '<br />';
echo $block->getStoreName() . '<br />';
echo $block->getStoreUrl() . '<br />';
echo $block->isStoreActive() . '<br />';

Using Object Manager


$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');

//var_dump($storeManager->getStore()->getData());
echo $storeManager->getStore()->getStoreId() . '<br />';
echo $storeManager->getStore()->getCode() . '<br />';
echo $storeManager->getStore()->getWebsiteId() . '<br />';
echo $storeManager->getStore()->getName() . '<br />';
echo $storeManager->getStore()->getStoreUrl() . '<br />';

Hope this helps. Thanks.