วิธีรับชื่อหมวดหมู่ปัจจุบันของผลิตภัณฑ์ในหน้ามุมมองผลิตภัณฑ์เหนือชื่อผลิตภัณฑ์ และให้เส้นทางของฉันแก่ฉันเพื่อรับชื่อหมวดหมู่ผลิตภัณฑ์ปัจจุบันใน Magento 2
วิธีรับชื่อหมวดหมู่ปัจจุบันของผลิตภัณฑ์ในหน้ามุมมองผลิตภัณฑ์เหนือชื่อผลิตภัณฑ์ และให้เส้นทางของฉันแก่ฉันเพื่อรับชื่อหมวดหมู่ผลิตภัณฑ์ปัจจุบันใน Magento 2
คำตอบ:
สร้างโมดูลที่กำหนดเองเช่นรหัสด้านล่าง
สร้างไฟล์โมดูลบล็อกเพื่อรับชื่อหมวดหมู่ปัจจุบัน
<?php
namespace Namespace\Modulename\Block;
class Blockname extends \Magento\Framework\View\Element\Template
{
protected $_registry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_registry = $registry;
parent::__construct($context, $data);
}
public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
}
?>
สร้างไฟล์ phtml ด้วยโค้ดด้านล่าง
<?php if ($currentCategory = $block->getCurrentCategory()): ?>
<div class="detail-category-name">
<?php echo $currentCategory->getName(); ?>
</div>
<?php endif; ?>
โทรไปไฟล์ phtml ผ่านไฟล์ xml
<referenceContainer name="product.info.main">
<block class="Namespace\Modulename\Block\Blockname" name="product.category.name" template="Magento_Catalog::product/view/yourfilename.phtml" >
</block>
</referenceContainer>
และในที่สุดคุณจะเห็นชื่อหมวดหมู่เหนือชื่อผลิตภัณฑ์ในหน้ารายละเอียดผลิตภัณฑ์
แจ้งให้เราทราบหากคุณมีข้อสงสัยใด ๆ
คุณควรจะสามารถรับรหัสหมวดหมู่ได้โดยใช้วิธี getCategoryIds () ในผลิตภัณฑ์ ตัวอย่างเช่นการอ้างอิง:
\Magento\Catalog\Model\Product::getCategoryIds();
ซึ่งหมายความว่าคุณควรจะสามารถโทร$product->getCategoryIds()
และกรองข้อมูลในบล็อกของคุณได้
นอกจากนี้ยังมีวิธีการที่เรียกว่าgetCategoryCollection()
ในรูปแบบเดียวกันซึ่งจะช่วยให้คุณวนผ่านหมวดหมู่เป็นวัตถุเต็มรูปแบบ ควรตัดชายกลางของการโหลดด้วย Id ของ
**Add XML Code Theme/namespace/Magento_Catalog/templates/product/view**
<block class="Magento\Catalog\Block\Product\View" name="product.info.category" after="product.price.final" template="product/view/current_category.phtml" />
**Create New File Theme/namespace/Magento_Catalog/templates/product/view**
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
$cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
echo $cat->getName();
}
?>