0

how to display all the products of a category in a phtml file using an external file in Magento 2

0

Create a block file at below location :

app/code/Company/Module/Block/Custom.php

<?php
namespace Company\Module\Block;
class Custom extends \Magento\Framework\View\Element\Template
{    
    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;
    }
}
?>

Now print the products using .phtml file :

$categoryId = 6; 
$categoryProducts = $block->getCategoryProducts($categoryId);
foreach ($categoryProducts as $product) {
    //print_r($product->getData());
    // printing category name and url
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.