Magento – Magento 2: Get all category products by category name

custom blockmagento2PHP

anyone knows how to load from my custom block.php all the products of a specific category,

I would like to get them by the name of the category and not by the id.

I tried to change the standard code used by magento \Magento\CatalogWidget\Block\Product\ProductsList

here is the code:

public function createCollection()
{
    $collection = $this->productCollectionFactory->create();
    $collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());

    $collection = $this->_addProductAttributesAndPrices($collection)
        ->addStoreFilter()
        ->setPageSize($this->getPageSize())
        ->setCurPage($this->getRequest()->getParam(self::PAGE_VAR_NAME, 1));

    $conditions = $this->getConditions();
    $conditions->collectValidatedAttributes($collection);
    $this->sqlBuilder->attachConditionToCollection($collection, $conditions);

    return $collection;
}

but this code get all categories products.

Best Answer

You need inject factory class \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory to __construct() function in order get category by name

  <?php
     namespace [VendorName]\[ModuleName]\Block;
         /**
          * @var Category
          */
     class Categories extends \Magento\Framework\View\Element\Template     
         protected $_categoryCollectionFactory;

        public function __construct(
             \Magento\Framework\View\Element\Template\Context $context,
             \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
 $categoryCollectionFactory,
             array $data = []
         ) {
            $this->categoryCollectionFactory = $categoryCollectionFactory;
             parent::__construct($context, $data);
         }

         public function getCategoriesbyName($name)
         {
            $categoryCollection = $this->categoryCollectionFactory->create();
             $categories = $categoryCollection->addAttributeToFilter('name', $name);
             return $categories;
         }
      }
Related Topic