Magento 2 – Change Title of Orders and Returns Page

magento2module

I have tried to change the title of the Orders and Returns page with XML with the following code.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <title>Orders and Tracking - Test</title>
    <link rel="canonical" src="http://www.extenderstore.com.au/sales/guest/form/" src_type="url"/>
</head>
<body>
    <referenceBlock name="page.main.title">
        <action method="setPageTitle">
            <argument translate="true" name="title" xsi:type="string">Orders and Tracking</argument>
        </action>
    </referenceBlock>
</body>
</page>

The canonical URL appears but the title does not. I have looked in vendor/magento/module-sales and I can't find an XML file which sets the title so I am assuming it is being done with a PHP function. I have done some further research and to override this I would need to make a module. How do I create this?

Best Answer

To change the title, you need to override the execute() function in \vendor\magento\module-sales\Controller\Guest\Form.php.

To do this, you need to create a new module:

/app/code/{vendor}/{module}/registration.php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '{vendor}_{module}',
    __DIR__
);

/app/code/{vendor}/{module}/etc/module.xml

Give preference to it:

/app/code/{vendor}/{module}/etc/di.xml

<?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\Sales\Controller\Guest\Form" type="{vendor}\{module}\Controller\Guest\Form"/>
</config>

Override the execute() function:

/app/code/{vendor}/{module}/Controller/Guest/Form.php

namespace {vendor}\{module}\Controller\Guest;

class Form extends Magento\Sales\Controller\Guest\Form
{
public function execute()
    {
        if ($this->_objectManager->get(\Magento\Customer\Model\Session::class)->isLoggedIn()) {
            return $this->resultRedirectFactory->create()->setPath('customer/account/');
        }
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('New Orders and Returns Title'));
        $this->_objectManager->get(\Magento\Sales\Helper\Guest::class)->getBreadcrumbs($resultPage);
        return $resultPage;
    }
}

run these 4 CLI commands afterwards in the exact same order to see the changes:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento setup:static-content:deploy

php bin/magento cache:flush

I haven't tested it, but it should work.