0

I'm attempting to override the canonical URL for a custom handler. I tried adding the following code via XML, but instead of overriding the default canonical URL, I now have both the default and the one I set. Does anyone have an idea on how to achieve this? Thank you.

<head>
    <link rel="canonical" src="https://mystore/test" src_type="url" />
</head>

2 Answers 2

0

Here's an example of what your layout XML might look like:

<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">
        <action method="addLinkRel">
            <argument name="rel" xsi:type="string">canonical</argument>
            <argument name="href" xsi:type="string">https://mystore/test</argument>
        </action>
    </referenceBlock>
</body>

In this example:

targets the head block. adds a link tag with the "canonical" relationship. https://mystore/test specifies the custom canonical URL.

0

Here's an example of how you can create the canonical URL in a custom layout handler in Magento 2:

Create or edit your custom layout XML file. This file should be located in your theme's app/design/frontend/{Vendor}/{Theme}/Magento_Theme/layout directory.

In the layout XML file, define your custom layout handler and use the block to set the canonical URL. Replace {Vendor} and {Theme} with your actual vendor and theme names.

app/design/frontend/{Vendor}/{Theme}/Magento_Theme/layout/{custom_layout}.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <!-- Your custom layout handler -->
        <referenceContainer name="head">
            <block class="Magento\Framework\View\Element\Text" name="custom_canonical" as="custom_canonical" before="-">
                <arguments>
                    <argument name="text" xsi:type="string"><![CDATA[<link rel="canonical" src="{your_custom_canonical_url}" />]]></argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>
  1. Replace {custom_layout} with the name of your custom layout handler.

  2. Replace {your_custom_canonical_url} with the desired canonical URL you want to set for the page.

  3. Clear the Magento cache after making changes to your layout XML files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.