Read magento 2 get store id phtml for more information.

This post is about how to programmatically get the current store in Magento 2. If you create a PHP script or Magento 2 module, you may need to check, which store is currently active (calls this script) and for which store you need to get or change values. This is done with the following lines of code.
magento 2 get store id phtml

Add a search to your Magento store

You can get the current store with every class that injects StoreManagerInterface. From a current store manager you can get all store related information you like. The object is different for each store frontend or even if you call it from backend. This code demonstrates how to create a simple class that injects this store manager interface:

namespace MyCompany\MyModule\Block;
class MyModel extends \Magento\Framework\View\Element\Template
    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);
     * Get store identifier
     * @return  int
    public function getStoreId()
        return $this->_storeManager->getStore()->getId();

Method getStoreId() returns id from the current active Magento 2 store.

If you want to check if this code was called from adminhtml context you can’t use isAdmin() anymore (this was the common option in Magento 1). If you need to check this, you can use a method based on \Magento\Framework\App\State class. Inject it and call getAreaCode to get the information it this class was called from adminhtml of the frontend. A simple if statement for this may look as follows:

if ($this->state->getAreaCode() == \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
    // Todo for adminhtml case

This checks if area code is equal adminhtml, which is defined as:

const AREA_CODE = 'adminhtml';

If you create Magento 2 modules for multi-store environments, this is essential. Different stores may display different product information and may also use complete different prices for the same products. I also showed you how to check if your code was called from adminhtml or frontend.

Searches related to Magento 2 get store id phtml

You may also like