今天我将推荐在Magento 2中获取特定类别产品的方法。允许您根据需要从当前或任何产品中获取列表。
现在,你需要打开我的自定义模块(块级Mageplaza_HelloWorld
),然后注入的对象\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
,\Magento\Catalog\Model\ProductRepository
并\Magento\Framework\Registry
在该块类的构造函数的类。
app/code/Mageplaza/HelloWorld/Block/HelloWorld.php
<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_categoryCollectionFactory;
protected $_productRepository;
protected $_registry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_categoryCollectionFactory = $categoryCollectionFactory;
$this->_productRepository = $productRepository;
$this->_registry = $registry;
parent::__construct($context, $data);
}
/**
* Get category collection
*
* @param bool $isActive
* @param bool|int $level
* @param bool|string $sortBy
* @param bool|int $pageSize
* @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
*/
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');
// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}
// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}
// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}
// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}
return $collection;
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
}
?>
如果您想使用当前产品,则getCurrentProduct()
功能处于活动状态。如果来自任何特定项目,请启用getProductById($id)
功能。之后,您可以从链接到该产品的类别ID中检索该类别的集合。在该.phtml
文件中,您需要添加以下代码段:
$productId = 1; // YOUR PRODUCT ID
$product = $block->getProductById($productId);
// for current product
// $product = $block->getCurrentProduct();
$categoryIds = $product->getCategoryIds();
$categories = $block->getCategoryCollection()
->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
echo $category->getName() . '<br>';
}
这就是您将用于在Magento 2中检索特定产品类别的所有内容。感谢您的阅读,如果有任何问题,请在下面评论。