Php 如何在magento 2.2.1中按类别id获取产品?

Php 如何在magento 2.2.1中按类别id获取产品?,php,magento-2.2.1,Php,Magento 2.2.1,我在Magento 2.2.1中工作,我试图通过类别id获取类别的产品集合 每次我打电话时,总会收到一个错误。请尝试以下代码: <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory'); $categoryHel

我在Magento 2.2.1中工作,我试图通过类别id获取类别的产品集合

每次我打电话时,总会收到一个错误。

请尝试以下代码:

<?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
}
?>

我希望它能帮助您

尝试以下代码:

<?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
}
?>


我希望它能帮助您在此处添加错误和代码。在此处添加错误和代码。