4

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";
}
11

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()->getStoreId(); 
$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

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

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.

  • 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
  • 2
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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