How to check if current url is homepage in Magento 2 Programmatically

To check if the current URL is the homepage in Magento 2, follow these steps.

  • Create the block class
  • Declare function in template .phtml file
  • Get output in index.php file

Create the block class

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();
}
}
?>

Declare function in template .phtml file

Add this code in your .phtml file.

if ($block->isHomePage()) {
// do something
}

Get output in index.php file

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.