PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

[FIXED] How to get products by category id in magento 2.2.1?

 October 16, 2022     magento2.2, php     No comments   

Issue

I am working in Magento 2.2.1, I am trying to get product-collection of a category by its category id.

Every time when i use to call using this example, I always get an error.


Solution

Try Below Code:

<?php
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');
$store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();

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

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

foreach ($categoryProducts as $product) 
{
    $imageUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();
    ?>

     <div class="product-container">
                  <a href="<?= $product->getProductUrl(); ?>">

                     <div class="new-arrivals-image"><img src="<?= $imageUrl;?>"></div>
                     <div class="product-name"><span class="name"><?= $product->getName(); ?></span></div>
                  </a>
                  <div class="price"><span class="pt"><?= $product->getPrice(); ?></span></div>
               </div>

<?php
}
?>

I hope it will help you



Answered By - Yatin Khullar
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing