Magento – add a code just after the body opening

magento2

What is the best way to add a code just after the body opening in Magento 2

I trayed

Content > design > configuration > Global > HTML Head

and added the code but not working

Also trayed to add it as a Widgets not working also.

Best Answer

I don't think there is any option to add script or any code just after body tag in magento from admin however you can add it by below mentioned method by editing/adding code.

You need to add provided code in your theme or module in default.xml inside body tag

path for default.xml in module app/code/Vendor/Module/view/frontend/layout/default.xml

path for default.xml in theme app/design/frontend/Vendor/Magento_Theme/layout/default.xml

and need to add phtml file where your custom code will be added.

path for phtml in your module app/code/Vendor/Module/view/frontend/templates/yourtemplate.phtml

path for phtml in your theme app/design/frontend/Vendor/Magento_Theme/templates/yourtemplate.phtml

Block need to be added inside body tag of default.xml

<referenceContainer name="after.body.start">
    <block class="Magento\Framework\View\Element\Template" name="blockname" template="Magento_Theme::yourtemplate.phtml"  before="-"/>
</referenceContainer>

Full example with default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="after.body.start">
            <block class="Magento\Framework\View\Element\Template" name="custombfb" template="Magento_Theme::html/bfd.phtml"  before="-"/>
        </referenceContainer>
    </body>
</page>

However there is available option in admin to place custom scripts like tracking code other analytics or chatbot code from admin in header and footer.

For header Admin->Content->Design->Configration->Edit Active Theme->HTML Head->Scripts and Style Sheets

For footer Admin->Content->Design->Configration->Edit Active Theme->Footer->Miscellaneous HTML

Related Topic