我在Magento 2.2.1工作,我正在尝试按类别ID获取类别的产品集合。
每当我用来拨打using this example时,我总是会收到错误。
答案 0 :(得分:0)
尝试以下代码:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');
$store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();
$categoryId = 47; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);
$categoryProducts = $category->getProductCollection()
->addAttributeToSelect('*');
foreach ($categoryProducts as $product)
{
$imageUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();
?>
<div class="product-container">
<a href="<?= $product->getProductUrl(); ?>">
<div class="new-arrivals-image"><img src="<?= $imageUrl;?>"></div>
<div class="product-name"><span class="name"><?= $product->getName(); ?></span></div>
</a>
<div class="price"><span class="pt"><?= $product->getPrice(); ?></span></div>
</div>
<?php
}
?>
我希望它能帮到你