如何向 Magento 2 添加自定义 JSON 代码?

How do I add custom JSON code to Magento 2?

我工作的一家公司使用 Magento 2 作为他们的 CMS。

他们想将 schema.org 标记添加到他们网站上的不同页面。

理想情况下,我想使用 JSON 添加。我会创建必要的 JSON 代码,然后将其添加到他们网站页面头部的某处。

是否可以将自定义代码添加到 Magento 2 中的不同页面?如果是这样,这是怎么做到的?

为此,您需要在所有页面的页眉中添加一个自定义 phtml 模板文件,并且需要检查每个页面类型。因此,您可以为不同的页面添加自己的自定义逻辑。请按照以下步骤操作:

第 1 步:在此处创建您的自定义模板文件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; ?>

第2步:使用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>