http://blog.chapagain.com.np/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 ofStoreManagerInterface in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld 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();
}
/**
* 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.
1
2
3
4
5
6
|
echo $block->getStoreId() . ‘<br />’;
echo $block->getStoreCode() . ‘<br />’;
echo $block->getWebsiteId() . ‘<br />’;
echo $block->getStoreName() . ‘<br />’;
echo $block->getStoreUrl() . ‘<br />’;
echo $block->isStoreActive() . ‘<br />’;
|