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 appcodeScommerceCustomBlockHead.php

namespace ScommerceCustomBlock; use MagentoFrameworkViewElementTemplate; class Head extends Template
{ /** * @var MagentoFrameworkViewAssetRepository */ protected $assetRepository; /** * Header constructor. * @param TemplateContext $context * @param array $data */ public function __construct( TemplateContext $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 appcodeScommerceCustomviewfrontendtemplateshead.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 appcodeScommerceCustomviewfrontendlayoutdefault.xml

<?xml version="1.0"?>
<page> <body> <referenceBlock name="head.additional"> <block template="head.phtml" class="ScommerceCustomBlockHead" name="scommerce_custom_block_head" /> </referenceBlock> </body>
</page>

Step 4 – Finally create your custom css under the following path appcodeScommerceCustomviewfrontendwebcsscustom.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.