1

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

Thanks.

1

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

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