Magento 2 – How to Set Meta Tags for Dynamic Pages in Custom Module

custommagento-2.1.7magento2module

I have created a custom module with admin grid form where data is entered and saved in database then it I retrieve to display at frontend.
So as an e.g I have followed for the frontend part this blog post toptal after success implementation I have individual pages like so: http://magento2.dev/blog/post/view/id/1, ../id/2, and so on…

All of the meta tags are being recorded in database and I need to be able to add this for example in my Controller:

public function execute()
{
    $post = $this->_post->create();
    $this->_coreRegistry->register(self::REGISTRY_KEY_STORE_ID, (int) $this->_request->getParam('id'));
    $resultPage = $this->_resultPageFactory->create();

    $resultPage->getConfig()->getTitle()->set($post->getMetaTitle());
    $resultPage->getConfig()->setDescription($post->getMetaDescription());
    $resultPage->getConfig()->setKeywords($post->getMetaKeywords());

    return $resultPage;
}

Where

$post->getMetaTitle(), $post->getMetaDescription() and
$post->getMetaKeywords()

are my functions from model Post that extends PostInterface.

But I had no luck when I var_dump($post->getMetaTitle()) I get NULL

Can anyone help me please?

Thank you.

Best Answer

From Block class, you can set Meta Title, Description and Keywords as below:

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

 /**
 * Prepare global layout
 *
 * @return $this
 */
protected function _prepareLayout()
{
    if($this->getSeoTitle())
        $this->_pageConfig->getTitle()->set('Meta Title');

    if($this->getMetaKeywords())        
        $this->_pageConfig->setKeywords('Meta Keywords');

    if($this->getMetaDescription())         
        $this->_pageConfig->setDescription('Meta Description');

    return parent::_prepareLayout();
}