We are trying to get product collection by category id.
Block:
protected $_categoryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
)
{
$this->_categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
public function getCategory($categoryId)
{
$category = $this->_categoryFactory->create();
$category->load($categoryId);
return $category;
}
public function getCategoryProducts($categoryId)
{
$products = $this->getCategory($categoryId)->getProductCollection();
$products->addAttributeToSelect('*');
return $products;
}
and in html:
$categoryId = 6; // fetching products in category id 6
$categoryProducts = $block->getCategoryProducts($categoryId);
foreach ($categoryProducts as $product) {
echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}
it works fine only if $categoryId
= the highest level in the category tree. But if I change $categoryId
to 2 (or 3... or etc but not last in category tree) it doesn't work.
How can I get it work?