How to call custom phtml file in head section

How to call custom phtml file in head section

Hello Friends,

Now I am coming with new things. may be you are always try to find on google but not find out but no worry i am always try to easy things which will help you in your development.

sometime client wants to require something different which is not available any where like add custom PHTML code into <head> tag.

I try to lots of search on google but not found so, i try to find out same things in code and full fill the client requirement. So, Here i am sharing those things with you for your speedy programming.

Please follow the below steps to add custom PHTML into <head> tag.

  1. Please copy core file to your theme.
    Core File  : vendor/magento/module-theme/view/base/templates/root.phtml
    Copy To :

    app/design/frontend/<VENDOR_NAME>/<THEME_NAME>/Magento_Theme/templates/root.phtml
    

    and replace with below code (This is taken from magento 2.3.3 version) like

    <?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ ?>
    <!doctype html>
    <html <?= /* @noEscape */ $htmlAttributes ?>>
        <head <?= /* @noEscape */ $headAttributes ?>>
            <?= /* @noEscape */ $requireJs ?>
            <?= /* @noEscape */ $headContent ?>
            <?= /* @noEscape */ $headAdditional ?>
            <?php echo $this->getLayout()
                            ->createBlock("Magento\Framework\View\Element\Template")
                            ->setTemplate("Magento_Theme::custom/head_custom.phtml")->toHtml(); ?>
        </head>
        <body data-container="body test"
              data-mage-init='{"loaderAjax": {}, "loader": { "icon": "<?= /* @noEscape */ $loaderIcon ?>"}}'
            <?= /* @noEscape */ $bodyAttributes ?>>
            <?= /* @noEscape */ $layoutContent ?>
        </body>
    </html></pre>
    <pre>
    

     

  2. Now create new phtml file under your theme like
    app/design/frontend/<VENDOR_NAME>/<THEME_NAME>/Magento_Theme/templates/custom/head_custom.phtml
    

    add your code and follow the step3

  3. Flush cache or run the below command
    php bin/magento setup:upgrade
    php bin/magento setup:static-content:deploy -f
    php bin/magento setup:di:compile (not required if you are in developer mode)
    php bin/magento cache:flush
    

    Now, Please check on fronted and you can see code in head section like

Hope This article will help you to fix your problem. You can leave a comment here.
Share On Facebook
Share On Twitter
Share On Linkedin

Post A Comment

Your email address will not be published. Required fields are marked *