2

I'm using Magento 2.2.6, How can I get the email ID of logged in user to show in header.

Thanks.

4

2 Answers 2

3

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.

enter image description here

<?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
    }
?>
4
  • Thanks, and how can I place it below the customer name in customer-welcome element.
    – user54226
    Commented Nov 22, 2018 at 14:32
  • user54226 Answer edited.
    – SHEESHRAM
    Commented May 31, 2019 at 8:12
  • @SHEESHRAM, why is there a screenshot of the code?
    – Black
    Commented Sep 17, 2019 at 12:58
  • Black Code is also there, Please check.
    – SHEESHRAM
    Commented Sep 19, 2019 at 8:54
3

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

Your Answer

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

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