Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Get Product Collection by Category ID in Magento 2

Vinh Jacker | 12-18-2024

Get Product Collection by Category ID

Today we’ll introduce a short but useful tutorial on how to get product collection by category ID in Magento 2. This is a quick way to acquire product collection that saves a lot of configuration time for the store admin and customers. That’s why you might see it is required by customers in an online store.

Regarding the fast development of Magento, the product collection is becoming increasingly important. This is because, in various projects, a product collection is usually required in different filters and requirements. Now let get an idea about product collection and how to get it by category ID in Magento 2.

**How to get Product Collection by Category ID in 3 steps: **

Now follow the below steps to get things done in a timely manner. You don’t need to change core code.

Step 1: Create Products.php block

In order to get the product collection by category ID, the first thing you would have to do is creating Products.php block. Follow this path: Mageplaza/HelloWorld/Block/Products.php

<?php
namespace Mageplaza\HelloWorld\Block;
class Products extends \Magento\Framework\View\Element\Template
{    
  
     /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productCollectionFactory;
  
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context);
    }
    
    
    public function getProductCollectionByCategories($ids)
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addCategoriesFilter(['in' => ids]);
        return $collection;
    }
}
  • Here, $ids is an array, which include category ids.
  • $_productCollectionFactory is an object of product collection factory which is used to get collection of product model.
  • addCategoriesFilter function to apply category filter.
  • $collection returns a collection of products which are assigned in given categories.

Step 2: Insert in phtml file

After the above step, you will have a collection in your block, now to get the Product collection in the block, follow the below snippet: Mageplaza/HelloWorld/view/frontend/templates/list.phtml

$ids = [1,2,3];
$categoryProducts = $block->getProductCollectionByCategories($ids);
foreach ($categoryProducts as $product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

Step 3: Flush Cache & Test result

Now, let’s flush cache and test result.

Conclusion

Above are the three steps, which could help you get product collection by Category ID in Magento 2. I hope this post is helpful for you when obtaining product collection. Share this tutorial with your friends to help them get product collection by category ID easily.

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services