将 UPC 属性添加到产品页面

时间:2021-05-23 23:40:43

标签: magento2 magento-2.3

在后端输入 UPC 编号时,我需要在我的产品页面上显示属性“UPC:”。我需要它显示在 SKU# 的正下方。我按照另一篇文章中的说明进行操作,通过使用他们的建议,我能够将 # 显示在正确的位置,但问题是标签 UPC: 与 SKU: 标签不同。自定义代码中缺少某些内容。如果其他人有比我尝试过的更好的解决方案,我愿意删除我尝试过的内容并从头开始。

以下是我使用的代码和文件。

您可以通过在catalog_product_view中的sku块之后创建块来显示自定义属性

在“app\design\frontend\VENDOR\THEME\Magento_Catalog\layout\catalog_product_view.xml”中创建catalog_product_view.xml

<?xml version="1.0"?>
<page layout="2columns-right" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Catalog\Block\Product\View" name="product_custom_attr" template="Magento_Catalog::product/view/custom_attr.phtml" after="-"/>
        </referenceContainer>
        <move element="product_custom_attr" destination="product.info.stock.sku" after="-"/>
    </body>
</page>

在“app\design\frontend\VENDOR\THEME\Magento_Catalog\templates\product\view\custom_attr.phtml”中创建 custom_attr.phtml 文件

<?php $_product = $this->getProduct(); ?><div class="product attribute">
<div class="value"><?php echo $_product->getData('upc_code') ?></div>
</div>

enter image description here

1 个答案:

答案 0 :(得分:0)

在应用程序/代码中创建自定义模块

在 app/code/Name/Module/view/frontend/layout 中创建 catelog_product_view.xml

<?xml version=""1.0""?>
<page xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" layout=""1column""
      xsi:noNamespaceSchemaLocation=""urn:magento:framework:View/Layout/etc/page_configuration.xsd"">
    <body>
        <referenceBlock name=""product.info.stock.sku"">
            <block class=""Name\Module\Block\Product\View"" name=""magenest_per_pox""
                   template=""Name_Module::product/view/custom_attr.phtml""/>
        </referenceBlock>
    </body>
</page>

在Name\Module\Block\Product\View.php中创建文件句柄并获取数据

在 app/code/Name/Module/view/frontend/templates/product/view/custom_attr.phtml 中创建 custom_attr.phtml

<?php
/** @var \Name\Module\Block\Product\View $block */
?>
<?php if ($block->getAttribute()) : ?>
    <div>
        <span>
            Test: <?php echo $block->getAttribute(); ?>
        </span>
    </div>
<?php endif; ?>