If you're looking to dynamically fetch your store's logo information in Magento 2, you've come to the right place. In this guide, we'll walk through the steps to obtain the Logo URL, Alt Text, and Logo Size programmatically in your Magento 2 store.
1. Logo URL:
To retrieve the URL of your store's logo in Magento 2, you can use the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore();
$baseUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$logoUrl = $baseUrl . 'theme-frontend-<Vendor>-<Theme>/images/logo.png';
echo $logoUrl;
?>
Replace <Vendor>
and <Theme>
with your actual vendor and theme names. This code fetches the base media URL and appends the path to your theme's logo file.
2. Alt Text:
To obtain the Alt Text associated with your store's logo, you can use the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$config = $objectManager->get('Magento\Theme\Block\Html\Header\Logo');
$altText = $config->getLogoAlt();
echo $altText;
?>
This code retrieves the Alt Text configured for the logo through the Magento\Theme\Block\Html\Header\Logo
class.
3. Logo Size:
To programmatically retrieve the width and height of your store's logo in Magento 2, you can use the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$config = $objectManager->get('Magento\Theme\Block\Html\Header\Logo');
$width = $config->getLogoWidth();
$height = $config->getLogoHeight();
echo "Width: {$width}, Height: {$height}";
?>
This code fetches the width and height of the logo using the getLogoWidth
and getLogoHeight
methods from the Magento\Theme\Block\Html\Header\Logo
class.
Important Note:
Using the Object Manager directly is not recommended for production code due to Magento best practices. It's advisable to utilize dependency injection and inject the necessary classes into your constructor for cleaner and more maintainable code.
Conclusion:
With these examples, you can easily retrieve the Logo URL, Alt Text, and Logo Size in Magento 2 programmatically. Remember to replace placeholder values with your actual theme information.