15/08/2022
We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
To check if the current URL is the homepage in Magento 2, follow these steps.
Directory
app/code/VendorName/ModuleName/Block/Demo.php
Contento of Demo.php
<?php
namespace VendorName\ModuleName\Block;
class Demo 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);
}
/**
* Check if the current URL is URL for home page
*
* @return bool
*/
public function isHomePage()
{
return $this->_logo->isHomePage();
}
}
?>
Add this code in your .phtml file.
if ($block->isHomePage()) {
// do something
}
Add the following code in the index.php file.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$demoBlock = $objectManager->get('VendorName\ModuleName\Block\Demo');
var_dump($demoBlock->isHomePage());
If you want any kind of help please visit our Magento 2 Development Service and get a Quote.