0

I want to add Dynamic URL in Admin->Content->Design->Configuration->HTML Head->Scripts and Style Sheets?

Actually, I want to add canonical tag throughout the website.

Here is the code:

<link rel="canonical" src="CurrentUrl here" />

Another way to add this is the XML file.

<head>
  <link rel="canonical" src="CurrentUrl here" src_type="url"/>
</head>

Please give me the clue if anyone used this approach.

1

If you want set that value dynamically, you have to with PHP. You only can be use static url like {{media_url}} or {{base_url}}. You can create a new module for doing dynamically and do the next:

Namespace/Module/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="after.body.start">
             <block class="Namespace\Module\Block\Content\Head\Canonical" name="vendor.namespace.head.canonical" template="Namespace_Module::head/canonical.phtml" />
         </referenceBlock>
    </body>
</page>

Namespace/Module/view/frontend/templates/head/canonical.phtml

<?php /** @var \Namespace\Module\Block\Content\Head\Canonical $block */?>
<?php if ($block->getCanonicalUrl()): ?>
    <link rel="canonical" href="<?php echo $block->getCanonicalUrl(); ?>">
<?php endif; ?>

Namespace/Module/Block/Content/Head/Canonical.php

...

public function getCanonicalUrl(){
   ...
}

...
  • Added same, But my phtml file not called. Block file called. But phtml file not called. – Ravi Soni Jul 2 '18 at 14:30
  • Use <referenceBlock name="header"> instead of <referenceContainer name="header">. – Sukumar Gorai Jul 2 '18 at 15:27
  • @Ravi sorry, I have updated my response with the new layout. – raumatbel Jul 2 '18 at 20:34
  • Thanks, I have updated <referenceBlock name="after.body.start"> to <referenceBlock name="head.additional"> – Ravi Soni Jul 2 '18 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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