Skip to content

Edit title and meta title from any page in magento 2

I’m trying to edit the h1 title and the meta title from any page in Magento 2.4.4. But it’s only working for the title because the head block is not found by my layout.

Here is what I do

<event name="layout_generate_blocks_after">
    <observer name="vendor_seo_custom_observer" instance="VendorSeoObserverChangeTitleObserver"/>
</event>




public function execute(Observer $observer)
{

    $currentWebsiteId = $this->storeManager->getStore()->getWebsiteId();
    $currentUrl = $this->urlInterface->getCurrentUrl();
    $currentUrlCleaned = str_replace('%','%%',$currentUrl);
    $this->loggerTitle->logInfo("Check url %s",[$currentUrlCleaned]);

    $tableName = $this->resourceConnection->getTableName('seo_meta');
    $select = $this->resourceConnection->select()
        ->from(['r' => $tableName], ['meta_id','request_path', 'meta_title','website_id','meta_description','title']);

    $data = $this->resourceConnection->fetchAll($select);
    foreach ($data as $row) {
        if($currentUrl == $row['request_path'] || $currentUrl.'/' == $row['request_path']){
            /** @var PageConfig $pageConfig */
            $layout = $observer->getData('layout');
            $blockTitle = $layout->getBlock('page.main.title'); //This block is found

            $blockMetaTitle = $layout->getBlock('head'); //This block value is false
            $h1Title = $row['title'];
            $metaTitle = $row['meta_title'];
            if(isset($blockTitle)){
                $blockTitle->setPageTitle($h1Title);
                $blockTitle->setTitle($h1Title);
                $this->loggerTitle->logSuccess('Apply title H1 %s',[$h1Title]);
            }
            if(isset($blockMetaTitle)){
                var_dump($blockMetaTitle);
                $blockMetaTitle->setMetaTitle($metaTitle);
                //$blockMetaTitle->setTitle($metaTitle);
                $this->loggerTitle->logSuccess('Apply Meta title  %s',[$metaTitle]);
            }
        }
    }
}