🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Get Product Collection by Category ID in Magento 2

By Sanjay JethvaUpdated on May 22, 2025 1 min read

You don’t know how the clients’ requirements can shoot out of nowhere. As a developer, you need to keep your tricks handy to satisfy the clients’ demands.

Here’s one such trick to get product collection by category ID in Magento 2. The solution given in the post lets you get the product collection with details like product name, price, etc. using the category ID.

I have used the below solution in my store to create a category of freebies, i.e., Free Magento Extensions!

You can use it to create a special category to feature a lifestyle or brand that is a curated collection of products from different categories. Or, filter products based on its type from the category.

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

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

$categoryId = 4; // YOUR CATEGORY ID
$category = $categoryFactory->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 can also set product position in a category in Magento 2 programmatically as the product position value determines the order of products on the category page.

I’d be very grateful if you helped share this helpful post on social media to fellow developers!

Thanks!

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.