Question

enter image description hereI want different top header section for guest and login user.

Guest user header option

"Hi Guest" + sign-in option

Login user header option

"Hi [User Name]"

How do I perform it programmatically?

Was it helpful?

Solution

You could achieve this requirement using a Plugin.

File - Vendor\Module\etc\di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Theme\Block\Html\Header" type="\Vendor\Module\Block\Html\MyCustomHeader" />
</config>

File - \Vendor\Module\Block\Html\MyCustomHeader.php

<?php

namespace Vendor\Module\Block\Html;


class MyCustomHeader extends \Magento\Theme\Block\Html\Header
{
    protected $_template = 'Magento_Theme::html/header.phtml';
    protected $_customerSession ;

    public function __construct(\Magento\Customer\Model\Session $customerSession, \Magento\Framework\View\Element\Template\Context $context, array $data = []) 
    {
        $this->_customerSession = $customerSession ;

        parent::__construct($context, $data);
    }


    /**
     * Custom Logic For Welcome Text
     *
     * @return string
     */
    public function getWelcome()
    {
        if($this->_customerSession->isLoggedIn()) {
            return parent::getWelcome();
        }
        else {
            return __('Hi Guest!');
        }
    }
}

OTHER TIPS

Actual file path vendor/magento/module-theme/view/frontend/templates/html/header.phtml

Override header.phtml file app/design/frontend/vendore/theme/Magento_Theme/templates/html/header.phtml

After that change

$welcomeMessage = $block->getWelcome();

to

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   $welcomeMessage = $block->getWelcome();
} 
else{
    $welcomeMessage = 'Hi Guest!';
}

sign-in option automatically remove for login customer.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top