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";
}
Jayreis
  • 705
  • 2
  • 27
  • 73

2 Answers2

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

Msquare
  • 9,063
  • 7
  • 25
  • 63
Manashvi Birla
  • 8,833
  • 9
  • 27
  • 53
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.

Rama Chandran M
  • 3,210
  • 13
  • 22
  • 38
  • please check it and let me know – Rama Chandran M Jun 28 '17 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 '17 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 '17 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. – Peter Karsai Jun 24 '20 at 08:22