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.

asked Jul 2, 2018 at 12:24

1 Answer 1

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(){
 ...
}
...
answered Jul 2, 2018 at 13:08
4
  • Added same, But my phtml file not called. Block file called. But phtml file not called. Commented Jul 2, 2018 at 14:30
  • Use <referenceBlock name="header"> instead of <referenceContainer name="header">. Commented Jul 2, 2018 at 15:27
  • @Ravi sorry, I have updated my response with the new layout. Commented Jul 2, 2018 at 20:34
  • Thanks, I have updated <referenceBlock name="after.body.start"> to <referenceBlock name="head.additional"> Commented Jul 2, 2018 at 20:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.