This article shows how we can check if the current page URL is homepage URL in Magento 2.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of Logo block class 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);
}
/**
* Check if current url is url for home page
*
* @return bool
*/
public function isHomePage()
{
return $this->_logo->isHomePage();
}
}
?>
See more functions in vendor/magento/module-theme/Block/Html/Header/Logo.php.
Now, we use can the function in our template (.phtml) file.
if ($block->isHomePage()) {
// do something
}
You can write the following code at the bottom of your site’s index.php file and see the output at the bottom of your page when you are in homepage or in any other page:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$helloWorldBlock = $objectManager->get('Chapagain\HelloWorld\Block\HelloWorld');
var_dump($helloWorldBlock->isHomePage());
Hope this helps. Thanks.