pablowilks2
pablowilks2

Reputation: 339

How do I add custom JSON code to Magento 2?

A company i am working with uses Magento 2 as their CMS.

They would like to add schema.org markup to different pages on their site.

Ideally, I would like to add using JSON. I would create the necessary JSON code and then add it to their site somewhere within the page's head section.

Is it possible to add custom code to different pages within Magento 2? If so, how is this done?

Upvotes: 0

Views: 1452

Answers (1)

Milan Chandro
Milan Chandro

Reputation: 2483

To do this, you need to add a custom phtml template file in the header for all pages and need to check each page types there. So you can add your own custom logic for different pages. Please follow the steps below:

Step 1: Create your custom template file here app/design/frontend/{Package}/{theme}/Magento_Theme/templates/html/custom_codes.phtml

<?php
    $getLayoutHandle = $this->getRequest()->getFullActionName(); // it returns all kind of pages handlers. just check and use by the following ways.
?>
<?php if($getLayoutHandle == 'cms_index_index'): ?>
    <!-- home page scripts here -->
<?php endif; ?>
<?php if($getLayoutHandle == 'catalog_category_view'): ?>
    <!-- product listing page scripts here -->
<?php endif; ?>
<?php if($getLayoutHandle == 'catalog_product_view'): ?>
    <!-- product details page scripts here -->
<?php endif; ?>

Step 2: Add to the above file in the header by using default.xml. app/design/frontend/{Package}/{theme}/Magento_Theme/layout/default.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>
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Template" name="custom_codes" template="Magento_Theme::html/custom_codes.phtml"/>
        </referenceBlock>
    </body>
</page>

Upvotes: 1

Related Questions