Add CSS or JS in Magento 2 via PHP instead of layout XML

How to add CSS or JS in magento 2 via php
Hi Guys, hope you are well, today we are going to talk about how to add CSS or JS in Magento using PHP code instead of layout xml. It took us a while to figure this out so we thought we should share this with our community. Please see below step by step guide which shows you how to do it -:

We are assuming you already know how to create a module in Magento 2, if not then please follow this link

Step 1 – Create a block class in your custom module in our case under \app\code\Scommerce\Custom\Block\Head.php

namespace Scommerce\Custom\Block;

use Magento\Framework\View\Element\Template;

class Head extends Template
{
    /**
     * @var \Magento\Framework\View\Asset\Repository
     */
    protected $assetRepository;

    /**
     * Header constructor.
     * @param Template\Context $context
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        array $data = []
    )
    {
        parent::__construct($context, $data);
        $this->assetRepository = $context->getAssetRepository();
    }

    /**
     * @return string
     */
    public function getCustomCSS()
    {
        $asset_repository = $this->assetRepository;
        $asset  = $asset_repository->createAsset('Scommerce_Custom::css/custom.css');
        $url    = $asset->getUrl();
        
        return $url;
    }
}

Step 2 – Create corresponding phtml for the class created in Step 1 \app\code\Scommerce\Custom\view\frontend\templates\head.phtml, this will add custom CSS, in the same way you can add custom JS or any HTML tag in the head section of your website

 
$url = $block->getCustomCSS();
if ($url):
    echo '<link rel="stylesheet" type="text/css" media="all" href="'.$block->getCustomCSS().'" />'
endif;

Step 3 – Create layout xml file to call the above phtml file in the head section of your website under \app\code\Scommerce\Custom\view\frontend\layout\default.xml

<?xml version="1.0"?>
<page>
   <body>
        <referenceBlock name="head.additional">
            <block template="head.phtml" class="Scommerce\Custom\Block\Head" name="scommerce_custom_block_head" />
        </referenceBlock>
   </body>
</page>

Step 4 – Finally create your custom css under the following path \app\code\Scommerce\Custom\view\frontend\web\css\custom.css

header.page-header{display:none}

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Scommerce

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.