I'm using Magento 2.2.6
, How can I get the email ID of logged in user to show in header.
Thanks.
I'm using Magento 2.2.6
, How can I get the email ID of logged in user to show in header.
Thanks.
First, create an instance in header.phtml file as below and also if more than one store is available and one wants to get mail in only one of the stores.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeID = $storeManager->getStore()->getStoreId();
$storeName = $storeManager->getStore()->getName();
?>
<?php
$customerSession = $om->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
echo $customerSession->getCustomer()->getEmail(); // get Email
}
?>
You need to inject \Magento\Customer\Model\Session $customerSession, class to get customer ID from customer session. Try this code.
protected $_customerSession;
public function __construct(
...
\Magento\Customer\Model\Session $customerSession,
...
) {
...
$this->_customerSession = $customerSession;
...
}
public function getCustomer()
{
echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID
$customerData = $this->_customerSession->getCustomer();
print_r($customerData->getData()); //Print current Customer Data
echo 'Customer Id: ' . $customerData->getId() . '<br/>';
echo 'Customer Name: ' . $customerData->getName() . '<br/>';
echo 'Customer Email: ' . $customerData->getEmail() . '<br/>';
echo 'Customer Group Id: ' . $customerData->getGroupId() . '<br/>';
}
NOTE: You only get customer id if customer logged in and customer session initialized