How to Add Custom CSS and JS Files on CMS Pages in Magento 2

How to Add Custom CSS and JS Files on CMS Pages in Magento 2
COMMENTS (0)
Tweet

In this blog, you will learn all the mandatory steps on how to include the custom CSS and JS files on CMS pages in your Magento 2 store. This task may seem a bit complicated to you, so here’s a simplified summary of all you need to know:

Step1

Create folder under app/code/

app/code/Folio3/CustomDesignFields

Step2

Create file registration.php and composer.json under app/code/Folio3/CustomDesignFields/
registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Folio3_CustomDesignFields',
    __DIR__
);
composer.json
{
    "name": "folio3/module-customdesignfields",
    "description": "Custom CMS Fields Module",
    "license": "proprietary",
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Folio3\\CustomDesignFields\\": ""
        },
        "files": [
            "registration.php"
        ]
    }
}

 

Step3

Create file module.xml under app/code/Folio3/CustomDesignFields/etc/ module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="Folio3_CustomDesignFields" setup_version="1.0.0"/>
</config>

 

Step4

Create file InstallSchema.php under app/code/Folio3/CustomDesignFields/Setup/ InstallSchema.php

<?php
 
namespace Folio3\CustomDesignFields\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface
{
 
            public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
            {
                        $installer = $setup;
                        $installer->startSetup();
                        $connection = $installer->getConnection();
 
                        $connection->addColumn('cms_page','page_css',['type' =>\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,'comment' => 'Page Css']);
                        $connection->addColumn('cms_page','page_js',['type' =>\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,'comment' => 'Page Js']);
            }
 
}

 

Step5

Create file cms_block_form.xml and cms_page_form.xml under app/code/Folio3/CustomDesignFields/view/adminhtml/ui_component/cms_page_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="content">
         <field name="page_css">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Page CSS</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="source" xsi:type="string">page</item>
                    <item name="dataScope" xsi:type="string">page_css</item>
                </item>
            </argument>
        </field>
         <field name="page_js">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Page JS</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="source" xsi:type="string">page</item>
                    <item name="dataScope" xsi:type="string">page_js</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

 

Step6:

Create Block file Page.php under app/code/Folio3/CustomDesignFields/Block/Cms/ to get specific page details

Page.php
<?php
namespace Folio3\CustomDesignFields\Block\Cms;
 
class Page extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Cms\Model\Page
     */
    protected $_page;
    /**
     * Page factory
     *
     * @var \Magento\Cms\Model\PageFactory
     */
    protected $_pageFactory;
 
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Cms\Model\PageFactory $pageFactory,
        \Magento\Cms\Model\Page $page,
        array $data = [])
    {
        parent::__construct($context, $data);
        $this->_page = $page;
        $this->_pageFactory = $pageFactory;
    }
 
    /**
     * Retrieve Page instance
     *
     * @return \Magento\Cms\Model\Page
     */
    public function getPage()
    {
        if (!$this->hasData('page')) {
            if ($this->getPageId()) {
                /** @var \Magento\Cms\Model\Page $page */
                $page = $this->_pageFactory->create();
                $page->setStoreId($this->_storeManager->getStore()->getId())->load($this->getPageId(), 'page_id');
            } else {
                $page = $this->_page;
            }
            $this->setData('page', $page);
        }
        return $this->getData('page');
    }
 
    public function getPageId(){
        return $this->_request->getParam('page_id');
    }
}
 

 

Step7

Create layout and template file to render new field content on frontend under Layout File

app/code/Folio3/CustomDesignFields/view/frontend/layout/cms_page_view.xml

<?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>
        <referenceContainer name="before.body.end">
            <block class="Folio3\CustomDesignFields\Block\Cms\Page"  name="cms.page.pagecssjs" template="Folio3_CustomDesignFields::cms/before_body_end.phtml"/>
        </referenceContainer>
    </body>
</page>
 

Template File
app/code/Folio3/CustomDesignFields/view/frontend/templates/cms/ before_body_end.phtml
<?php
    $page = $this->getPage();
?>
<style>
    <?php if($pageCss = trim($page->getPageCss())):?>
        <?php echo $pageCss ;?>
    <?php endif;?>
    
</style>
<?php if($js = $page->getPageJs()):?>
    <script>
        <?php echo $js; ?>
    </script>
<?php endif;?>                                                               

 

And that’s it!

Please feel free to comment or reach out if you have any questions. If you need any help with customizing your Magento or Magento 2 web store, please get in touch with us.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812