5

In Magento 2 I have a phtml file I am trying to get what store view is currently being seen by the website visitor. However it does not seem to work. I dont want to have to create a whole module or plugin .

if (Mage::app()->getStore()->getId() > '1')
{
      echo "you are 1";
}
elseif (Mage::app()->getStore()->getId() > '2')
{
     echo "you are 2";
}
 else
{
   echo "you are not 1 or 2";
}
0

2 Answers 2

13

You can fetch the current store id and the store name in phtml file (using ObjectManager) like below :

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$storeManager  = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeID       = $storeManager->getStore()->getId(); 
$storeName     = $storeManager->getStore()->getName();

you can use this $storeID according to your condition :

if ($storeID > '1')
{
    // your logic
}

However, this is not a proper approach. A much cleaner way would be to use a block or a helper

1
  • 4
    It's considered bad practice to use ObjectManager this way. See here for more detail.
    – Holly
    Apr 12, 2018 at 17:44
6

you can inject the Magento\Store\Model\StoreManagerInterf‌​ace in your constructor to get the store view in block and send to phtml.

protected $_storeManagerInterface;

public function __construct(
     \Magento\Store\Model\StoreManagerInterf‌​ace $storeManagerInterface
    )
{
    $this->_storeManagerInterface = $storeManagerInterface;

}

Then in your code you can do:

$currentStore = $this->_storeManagerInterface->getStore();
$currentStoreId = $currentStore->getId();

based on store id you can write a condition.

4
  • please check it and let me know Jun 28, 2017 at 17:50
  • So do I put the public_function in the top of the contact.phtml page or ..? Because when I put it in to the file it makes the page load blank with no errors.
    – Jayreis
    Jun 28, 2017 at 17:56
  • 3
    The class Magento\Framework\View\Element\Template already includes an instance of Magento\Store\Model\StoreManagerInterf‌​ace, which should be available to all child block classes. It is a private property though and won't be available in the template without creating creating a public function to return it. This can't be accomplished from within the template.
    – Pmclain
    Jun 28, 2017 at 18:58
  • _storeManager in Magento\Framework\View\Element\Template is a protected property not (at least in 2.3.4), so it should work out of the box. Jun 24, 2020 at 8:22

Your Answer

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

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