Having unique content Play Key role important in SEO. Many times store owners get content duplication issues which are common SEO issues in e-commerce stores that’s why you need to add canonical Links to avoid duplicate content to improve your e-commerce site ranking. So let’s follow the steps that are given below to Add Canonical Tag To CMS Pages On Magento 2?
Step 1: Create a custom module
Step 2: Create helper file in your custom module:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php declare(strict_types=1); namespace Webiators\AddCanonicalTag\Helper; use Magento\Cms\Model\Page; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; /** * Class Canonical * @package Webiators\AddCanonicalTag\Helper */ class Canonical extends AbstractHelper { /** * @var Page */ protected $cmsPage; /** * Canonical constructor. * @param Context $context * @param Page $cmsPage */ public function __construct( Context $context, Page $cmsPage ) { $this->cmsPage = $cmsPage; parent::__construct($context); } /** * This method is used in XML layout. * @return string */ public function getCanonicalForAllCmsPages(): string { if ($this->cmsPage->getId()) { return $this->createLink( $this->scopeConfig->getValue('web/secure/base_url') . $this->cmsPage->getIdentifier() ); } return ''; } /** * @param $url * @return string */ protected function createLink($url): string { return '<link rel="canonical" href="' . $url . '" />'; } } |
Step 3: Create layout file name default.xml in your custom module:
Webiators/AddCanonicalTag/view/frontend/layout/default.xml
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="head.additional"> <container name="canonical.url.cms.page.container"> <block class="Magento\Framework\View\Element\Text" name="canonical.url.cms.page"> <arguments> <argument name="label" xsi:type="string">Adding canonical link with base URL</argument> <argument name="text" xsi:type="helper" helper="Webiators\AddCanonicalTag \Helper\Canonical::getCanonicalForAllCmsPages"/> </arguments> </block> </container> </referenceBlock> </body> </page> |
Thank You!
Hit 5 Stars if you find this post helpful
0 (based on 0 Reviews)