Magento2 – How to Add Tag in Homepage Head

magento2magento2.2.2

I'm having a lot of problems adding an html tag in head section only on homepage layout (that's defined in my custom theme as page layout). I'm using M2 v. 2.2

In default.xml is defined

<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Template" name="head.additional.fonts" template="Infortis_Base::html/header/fonts.phtml" after="head.additional.asset-wrapper" />
</referenceBlock>

and I added a block to edit and insert an html tag:

<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Template" name="head.additional.fonts" template="Infortis_Base::html/header/fonts.phtml" after="head.additional.asset-wrapper" />
    <block class="Magento\Framework\View\Element\Template" name="head.additional.metas" template="Infortis_Base::html/header/metas.phtml" before="head.additional.asset-wrapper" />
</referenceBlock>

so that I would be able to change the phtml template inside the home xml page layout but if I reference the block it doesn't change.

Any help? I'm on this from 2 days and it driving me crazy. THANKS

Best Answer

You shouldn't use <referenceBlock name="head.additional"> in default.xml. Because it's the place to define head.additional by default. Instead, if you want to show it on homepage only, you should place your code on cms_index_index.xml. So that:

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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">
            <block class="Magento\Framework\View\Element\Template" name="head.additional.fonts" template="Infortis_Base::html/header/fonts.phtml" after="head.additional.asset-wrapper" />
        </referenceBlock>
    </body>
</page>

Put these code into app/design/frontend/<Vendor_Name>/<Theme_Name>/Magento_Cms/layout/cms_index_index.xml. Then clear cache and refresh. Your block should appear.

Related Topic