Magento – Display Parent Category Title on Sub Category Page Title

categorymagento2

How to change Magento 2 Sub Category Page Title? I want to show parent category title when visiting sub-category.

Best Answer

You can try the below code.

Step1 - Creating registration.php file in the following path - app/code/Training/Changecattitle.

<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE,'Training_Changecattitle',__DIR__);

Step2 - Creating module.xml file in the following path - app/code/Training/Changecattitle/etc.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Training_Changecattitle" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Step3 - Creating di.xml file to overwrite \Magento\Catalog\Block\Category\View in the following path - app/code/Training/Changecattitle/etc.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Category\View" type="Training\Changecattitle\Block\Category\View" />
</config>

Step4 - Creating View.php file in the following path - app/code/Training/Changecattitle/Block/Category.

    <?php
    /**
     * Copyright © 2016 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */
    namespace Training\Changecattitle\Block\Category;

    /**
     * Class View
     * @package Magento\Catalog\Block\Category
     */
    class View extends \Magento\Catalog\Block\Category\View
    {

        protected function _prepareLayout()
        {
            \Magento\Framework\View\Element\Template::_prepareLayout();

            $this->getLayout()->createBlock('Magento\Catalog\Block\Breadcrumbs');

            $category = $this->getCurrentCategory();
            if ($category) {
                $pageMainTitle = $this->getLayout()->getBlock('page.main.title');
 // Here you can set custom page title in your case you can get root category page title and set here.  
                 $pageMainTitle->setPageTitle($this->getCurrentCategory()->getName());
            }

            return $this;
        }


    }

Run setup upgrade script.

Clear Cache.

Give folder permission 0777 to var folder.

you can download full module from github link https://github.com/jothibasuj/Mage2-Custom-Modules/tree/master/Mage2-Custom-Modules/Training/Changecattitle