General

How to Get Product Collection by Category ID in Magento 2

Hello Magento Friends?,

How’s the weekend going on? As always welcome to Magento Tutorial Blog. Today I am going to explain to you How to Get Product Collection by Category ID in Magento 2. Also, go through our previous blog article about Magento 2: How to Get System Configuration Value Into JS. Let’s Dive In?

OPEN NEW SALES CHANNEL for your Magento store in 3 EASY STEPS!

Introduction:

The client is like a small child. We have to satisfy all the needs of our clients. Developers should take care of all the requirements of the client’s demands. For that, I am going to illustrate to you all how to Get Product Collection by Category ID in Magento 2. In this rapid development in the online business, there are mandatory features required like a product collection option with various filters applied to it. Else the products are filtered on the basis of its category. 

With the help of this article you can easily get the product collection with all the information like product price, name, etc. by using the category ID. For your illustration visit Magento 2 Extensions where I have implemented 

Steps to Get Product Collection by Category ID in Magento 2:

Method 1: Using Class

Create one block file on our custom extension
add Blockname.php in the following path

app\code\Vendor\Extension\Block\Blockname.php

now add following code

<?php
namespace Vendor\Extension\Block;

use Magento\Framework\View\Element\Template;

class Blockname extends Template
{

 protected $categoryFactory;

 public function __construct(
  \Magento\Backend\Block\Template\Context $context,
  \Magento\Catalog\Model\CategoryFactory

 )
 {
  $this->categoryFactory = $CategoryFactory;
  parent::__construct($context);
 }

 public function getProductCollectionFromCategory($categoryId) {
  $category = $this->categoryFactory->create()->load($categoryId);
  return $category->getProductCollection()->addAttributeToSelect('*');

 }

 

}

After this you need to phtml file and add the following code into a file:

$block->getProductCollectionFromCategory(4); // YOUR CATEGORY ID

foreach ($categoryProducts as $product) {
    // get Product data
    print_r($product->getData());

    echo $product->getName();
}

Method 2: Using Object Manager

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$categorysFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');

$categoryId = 4; // YOUR CATEGORY ID
$category = $categorysFactory->create()->load($categoryId);

$categoryProducts = $category->getProductCollection()
    ->addAttributeToSelect('*');

foreach ($categoryProducts as $product) {
    // get Product data
    print_r($product->getData());

    echo $product->getName();
}

That’s It You are done.

Note: Using ObjectManager for Magento development is not recommended by us and Magento. This is just for Knowledge purposes.

Over to You:

Therefore, after you implement the above step you will easily be able to get Product Collection by Category ID in Magento 2. If any difficulties then do comment down in the comment section below. Share the article with your Magento developer friends and help them to get Product Collection by Category ID in Magento 2.

Happy Coding! 

Click to rate this post!
[Total: 15 Average: 4.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • Hi , Some customers having one plan named as cplan, I need a product collection based on cplan . The plan same as subscription ,then how to get product collection based on cplan.

  • Hi,

    $categoryId = 4; // YOUR CATEGORY ID
    $category = $categoryFactory->create()->load($categoryId);

    Instead of static category id, for example, as 4, I want to dynamic category id.
    How to do that?

    Please help, it will be really helpful for me.
    Thank you.

    • You have to modify the code of "getProductCollectionFromCategory" function according to your requirement.

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 day ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

7 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

7 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago