Magento – How to get Meta data in title.phtml on Magento2

magento2metameta-tags

I am trying to get the current pages meta data in title.phtml on Magento 2 so that I can have a sub title and slight description on the page.

But I cant find anything for how to retrieve this information, only how to set it.

I have tried things like:

$this->pageConfig->getTitle();

and

$this->getLayout()->getBlock('head')->getTitle();

and

$resultPage->getConfig()->getTitle()

But all without success. I know this is all quite new at the moment but can anyone tell me how to do this?

Best Answer

A way to get the meta data could be:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_page = $objectManager->get('Magento\Cms\Model\Page');

$_meta_title = strip_tags($_page->getMetaTitle());
$_meta_description = strip_tags($_page->getMetaDescription());
$_meta_keywords = strip_tags($_page->getMetaKeywords());

However this does not take into account the default settings under Content > Design > Configuration > HTML Head

This only works for cms pages, i guess.

Finally i used this in my case:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_page_config = $objectManager->get('Magento\Framework\View\Page\Config');

$_meta_title = strip_tags($_page_config->getTitle()->getShort());
$_meta_description = strip_tags($_page_config->getDescription());
$_meta_keywords = strip_tags($_page_config->getKeywords());

Have look in the Magento\Framework\View\Page\Config i think there is literally a getMetadata method.

Related Topic