Solved: How to add custom script just after the opening head tag in Magento 2

Solved: How to add custom script just after the opening head tag in Magento 2

There are many times when you would want to add a custom <script> just before the opening head tag in Magento but no matter what you do, the script will always get added after Magento loads its requireJS which isn’t much helpful, but in this article, I will share the steps you can take to ensure that your script gets added right after the opening <head> tag – yes, even before Magento injects its requireJS.

By default Magento 2 uses the root.phtml file to setup head content accordingly, which is located in vendor/magento/module-theme/view/base/templates/root.phtml (unless it has been overridden in your custom theme). The content of the root.phtml is as follows:

<?php
<script>
    var BASE_URL = '<?= $block->escapeUrl($block->getBaseUrl()) ?>';
    var require = {
        "baseUrl": "<?= /* @escapeNotVerified */ $block->getViewFileUrl('/') ?>"
    };
</script>

This file contains the $requireJs variable and block and the require.js block is defined in vendor/Magento/module-theme/view/frontend/layout/default.xml content of which is as follows:

<block name="require.js" class="Magento\Framework\View\Element\Template" template="Magento_Theme::page/js/require_js.phtml" />

Now, there are two possible solutions to override the file:

  1. By overriding the file in your custom theme
  2. By creating a simple module (preferred)

Override require_js.phtml in your custom theme

To override the the file in your custom theme, copy require_js.phtml from vendor/magento/module-theme/view/frontend/templates/page/js to your theme app/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/ and finally, put your custom JS code just above the requireJS block i.e.

<script>
    console.log("Hello World!"); 
    var require = {
        "baseUrl": "<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
    };
</script>

Override require_js.phtml in a custom module

Create default.xml in view/frontend/layout/ and add the following code:

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="require.js">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Shoman_CustomScript::code.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

As you can see, in the code above, we are setting a new template file code.phtml for the require.js block.

Next, go ahead and create the code.phtml file in ./view/frontend/templates and add the custom code as follows:

<?php
<!-- My Custom Script start -->
<script type="text/javascript">
console.log("Hello World!");
</script>
<!-- My Custom Script end -->

<script>
    var BASE_URL = '<?= $block->escapeUrl($block->getBaseUrl()) ?>';
    var require = {
        "baseUrl": "<?= /* @escapeNotVerified */ $block->getViewFileUrl('/') ?>"
    };
</script>

I have created a simple module that does the job already and you can download it from here: https://github.com/shoaibrehman/Magento2-OneTrust-Cookies – this module primarily focus on integrating OneTrust Cookie Policy script so feel free to replace the content of code.phtml file as per your needs or you can fork the module and modify it as per your needs!

Solved: PHP Fatal Error: Class ‘CLI’ was not found in ‘bin\Magento’ on line 31

Solved: PHP Fatal Error: Class ‘CLI’ was not found in ‘bin\Magento’ on line 31

Magento2 is full of surprises and I am loving and hating it at the same time. I fix one issue and another issue comes up sooner or later.

Mostly, I have been using Ubuntu for Magento 2 development but I decided to try it on Windows to test the platform performance. Installation was nice and easy and I was able to install demo data without any issue.

After setting up the initial version, I decided to create my own extension which involved a few frontend templating. Everything was normal until I ran ‘php bin\magento setup:di:compile’. Screenshot below.

Magento CLI fatal error

I was served with a fatal error and after scratching my head a few times – and of course hitting on the wall a few times, I decided to remove var/generation directory. It all went fine this time. Alright, so to cut the long store short, do the following:

STEPS:

  1. Don’t panic
  2. Take a deep breath
  3. Remove {magento_directory}/var/generation/
  4. Run ‘php bin/magento setup:di:compile’ again

Did it fix your issue? Leave a comment below to let others know :)

Solved: Class Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory does not exist

Solved: Class Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory does not exist

Magento 2 generates Factory classes inside var/generation directory. So, if there is folder permission issue or folder owner issue with that directory then the factory class cannot be generated and you get such error.

When you clear var/generation directory and set appropriate permission to it then this error should be solved.

T0 update the directory permissions, do the following:

chown-ubuntu-terminal

  • Open your linux terminal, on Ubuntu you can access it by pressing Ctrl + Alt + T
  • On the terminal  window, Go to your Apache/Nginx directory e.g. var/www/html/{Magento Directory}
  • Type ‘sudo chmod 775 -R {Magento Directory}/’ and hit enter.
  • Alternatively, you can apply 777 permission to your {Magento Directory} as well but it is not recommended.