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!