PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

[FIXED] How do I add custom JSON code to Magento 2?

 August 23, 2022     content-management-system, magento2, schema.org, structured-data     No comments   

Issue

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?


Solution

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>


Answered By - Milan Chandro
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing