2

Is their any way we can get current page title in magento 2 ?

1
  • Is their any way i can use di method & achieve the same ? Feb 6, 2021 at 10:30

2 Answers 2

2

Quick but not recommended

You can call the following directly in your file:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$title = $objectManager->get('Magento\Framework\View\Page\Title');

+++++++++++++++++++++++++++++

Via DI

protected $_pageTitle;

public function __construct(
    \Magento\Framework\View\Page\Title $pageTitle
) {
    $this->_pageTitle = $pageTitle;
}


public function getTitle()
{
    return $this->_pageTitle->getShort();
}
2
  • Is their any way i can use di method & achieve the same ? Feb 6, 2021 at 10:08
  • @HamendraSunthwal Please check my answer and if it works give thumbs up. Feb 6, 2021 at 13:15
0

You can set and get page title using observer like below

Step 1: Please create events.xml file under PackageName/CustomTitle/etc/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="layout_generate_blocks_after">
       <observer name="hideorders" instance="PackageName\CustomTitle\Observer\Currentpagetitle" />
   </event>
</config>

Step 2: Please create Currentpagetitle.php file under PackageName/CustomTitle/Observer/

<?php
namespace PackageName\CustomTitle\Observer;
 
use Magento\Framework\Event\ObserverInterface;
 
class Currentpagetitle implements ObserverInterface
{
    protected $_pageConfig;

    public function __construct(
        \Magento\Framework\View\Page\Config $pageConfig
    ) {
        $this->_pageConfig = $pageConfig;   
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getData('layout');
        $pageMainTitle = $layout->getBlock('page.main.title');
        if ($pageMainTitle)
        {
            $oldTitle = $pageMainTitle->getPageTitle();//Get current page title

            //Set custom meta title and page title like below
            $this->_pageConfig->getTitle()->set($oldTitle. __('- Custom Title'));
            $pageMainTitle->setPageTitle(
                $oldTitle
                . __('- Custom Title')
            );
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.