Question

I am developing a custom theme which never displays the breadcrumb, so I removed it in the default.xml:

<referenceBlock name="breadcrumbs" remove="true" />

This caused that the category view page to have empty meta title. Is there a way to programmatically set the meta title for this type of page?

Was it helpful?

Solution

Following the suggestion of Alex Constantinescu in his answer I managed to set the category title in the category view page.

Firstly I created a custom block for this purpose:

<?php
namespace Custom\Content\Block;

class Title extends \Magento\Framework\View\Element\Template
{
    /**
     * @param \Magento\Framework\Registry $registry
     */
    protected $_registry;

    function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = [],
        \Magento\Framework\Registry $registry
    )
    {
        parent::__construct($context, $data);
        $this->_registry = $registry;
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        $category = $this->_registry->registry('current_category');
        if($category)
        {
            $category->getMetaTitle();
            $metaTitle = empty($category->getMetaTitle()) ? $category->getName() : $category->getMetaTitle();
            $this->pageConfig->getTitle()->set($metaTitle);
        }
    }
}

In the prepareLayout method I retrieve the current category and set the meta title (if present) or the category name as meta title.

Then I included the block in my catalog_category_view.xml file, without specifying a template:

<referenceBlock name="main">
    <block name="category.title" class="Custom\Content\Block\Title" />
</referenceBlock>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top