I want to add canonical tag for all cms pages. Currently canonical tag enabled for category and product page.
How to do this?
Go to Admin Panel > Content > Pages > Opne CMS Page > Design > Layout Update XML
Add code in there
<head>
<link rel="canonical" src="www.example.com/page-url-key" src_type="url"/>
</head>
Update:
To add in Catalog Search Result Page.
Add following code into catalogsearch_result_index.xml
in
app/design/frontend/Vendor/theme/Magento_CatalogSearch/layout/catalogsearch_result_index.xml
<referenceBlock name="head.additional">
<block class="Magento\Framework\View\Element\Template" name="search_canonical" template="Magento_CatalogSearch::canonical.phtml" />
</referenceBlock>
Create PHTML file for canonical URL code.
app/design/frontend/Vendor/theme/Magento_CatalogSearch/templates/canonical.phtml
<link rel="canonical" href="<?php echo $this->getBaseUrl().'catalogsearch/result/'; ?>" />
Don't forget to flush the cache.
You can do it from the Backend in Layout Update XML using the following snippet.
Due the fact that only referenceContainer, container, update, move elements are allowed.
<container name="canonical.url.container">
<block class="Magento\Framework\View\Element\Text" name="canonical.url">
<arguments>
<argument name="text" xsi:type="string"><![CDATA[<link rel="canonical" href="https://example.com" />]]></argument>
</arguments>
</block>
</container>
<move element="canonical.url.container" destination="head.additional" before="-" />
Use this module for the dynamic canonical link for each cms page-
https://github.com/zaxcpro/cms-canonical
Thanks
You can use our extension (Canonical URL extension for Magento 2 by Ecwhim):
https://www.ecwhim.com/magento-2-canonical-url-extension.html
It will help you add a canonical url to CMS pages.