This article shows how we can get the URL and ALT text of a Logo of the Magento 2 website. The article also include code to fetch Logo Height and Width.
Logo Image Width and Logo Image Height is fetched from Configuration Settings (Stores -> Settings -> Configuartion -> General -> Design -> Header
).
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of Logo block in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_logo;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Theme\Block\Html\Header\Logo $logo,
array $data = []
)
{
$this->_logo = $logo;
parent::__construct($context, $data);
}
/**
* Get logo image URL
*
* @return string
*/
public function getLogoSrc()
{
return $this->_logo->getLogoSrc();
}
/**
* Get logo text
*
* @return string
*/
public function getLogoAlt()
{
return $this->_logo->getLogoAlt();
}
/**
* Get logo width
*
* @return int
*/
public function getLogoWidth()
{
return $this->_logo->getLogoWidth();
}
/**
* Get logo height
*
* @return int
*/
public function getLogoHeight()
{
return $this->_logo->getLogoHeight();
}
}
?>
See more functions in vendor/magento/module-theme/Block/Html/Header/Logo.php.
Now, we use can the function in our template (.phtml) file.
echo $block->getLogoSrc() . '<br />';
echo $block->getLogoAlt() . '<br />';
echo $block->getLogoWidth() . '<br />';
echo $block->getLogoHeight() . '<br />';
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$logo = $objectManager->get('\Magento\Theme\Block\Html\Header\Logo');
echo $logo->getLogoSrc() . '<br />';
echo $logo->getLogoAlt() . '<br />';
echo $logo->getLogoWidth() . '<br />';
echo $logo->getLogoHeight() . '<br />';
Hope this helps. Thanks.