How to Customise Header for guest and logged in user in magento2 programmatically?
-
07-03-2021 - |
La 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!');
}
}
}
Autres conseils
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.
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange