How To Get Product Collection In Magento 2

In the previous article, we learned about How To Make Custom Page Layout In Magento 2. Today, we will introduce you about How to get product collection in Magento 2.

I think you should read How To Create New Theme In Magento 2 first.

Make block get product collection

Create file app/code/<vendor_name>/<module_name>/Block/Products.php should look like:

<?php
namespace Magetop\Themes\Block;
use Magento\Framework\View\Element\Template;
 
class Products extends Template
{
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\Product\Visibility $visibility,
        \Magento\Catalog\Block\Product\ListProduct $abstractProduct,
        array $data = []
    ) {
        $this->_productModelFactory = $productFactory;
        $this->_productVisible = $visibility;
        parent::__construct($context, $data);
        $this->absblock = $abstractProduct;
    }
    public function getBestSellerProducts($categoryID = null)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();    
        $collection = $objectManager->get('\Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory')->create()->setModel('Magento\Catalog\Model\Product');
        $producIds = array();
        foreach ($collection as $product) {
            $producIds[] = $product->getProductId();
        }
        $model = $this->_productModelFactory->create();
        $storeId = $model->getStoreId();
        $collection = $model->getCollection();
        $collection->setVisibility($this->_productVisible->getVisibleInCatalogIds());
        $collection->setStoreId($storeId)
            ->addAttributeToSelect('*')
            ->addStoreFilter($storeId);
 
        $collection = $collection->addStoreFilter()->addAttributeToFilter('entity_id', array('in' => $producIds));
        if($categoryID && $categoryID != 0){
            /**
             * @var \Magento\Catalog\Model\Category $catModel
             */
            $catModel = $this->_categoryFactory->create();
            $catCollection = $catModel->load($categoryID);
            $collection->addCategoryFilter($catCollection);
        }
        $collection->setPageSize(10);
        return $collection;
    }
}

We’ll get BestSeller products on the home page. So go to backend then paste below code to content home page.

{{block class="Magetop\Themes\Block\Products" name="bestseller.colection" template="Magetop_Themes::product/bestseller.phtml"}}

After create file <theme_dir>/Magento_Theme/templates/product/bestseller.phtml should look like:

<?php
$_productCollection = $block->getBestSellerProducts();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<?php if ($_productCollection->count()): ?>
    <div class="products wrapper grid products-grid">
        <ol class="products list items product-items">
            <?php foreach ($_productCollection as $_product): ?>
            <li class="item product product-item">
                <div class="product-item-info" data-container="product-grid">
                    <a href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                        <?php echo $block->absblock->getImage($_product,'category_page_grid')->toHtml(); ?>
                    </a>
                    <div class="product details product-item-details">
                        <?php
                            $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                        ?>
                        <strong class="product name product-item-name">
                            <a class="product-item-link"
                               href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>">
                                <?= /* @escapeNotVerified */ $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
                            </a>
                        </strong>
                        <?= $block->absblock->getReviewsSummaryHtml($_product,'short',true) ?>
                        <?= /* @escapeNotVerified */ $block->absblock->getProductPrice($_product) ?>
                        <div class="product-item-inner">
                            <div class="product actions product-item-actions">
                                <div class="actions-primary">
                                    <?php if ($_product->isSaleable()): ?>
                                        <?php $postParams = $block->absblock->getAddToCartPostParams($_product); ?>
                                        <form data-role="tocart-form" data-product-sku="<?= $block->escapeHtml($_product->getSku()) ?>" action="<?= /* @NoEscape */ $postParams['action'] ?>" method="post">
                                            <input type="hidden" name="product" value="<?= /* @escapeNotVerified */ $postParams['data']['product'] ?>">
                                            <?= $block->absblock->getBlockHtml('formkey') ?>
                                            <button type="submit"
                                                    title="<?= __('Add to Cart') ?>"
                                                    class="action tocart primary">
                                                <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php if ($_product->isAvailable()): ?>
                                            <div class="stock available"><span><?= /* @escapeNotVerified */ __('In stock') ?></span></div>
                                        <?php else: ?>
                                            <div class="stock unavailable"><span><?= /* @escapeNotVerified */ __('Out of stock') ?></span></div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                <div data-role="add-to-links" class="actions-secondary">
                                    <?php if ($addToBlock = $block->absblock->getChildBlock('addto')): ?>
                                        <?= $addToBlock->setProduct($_product)->getChildHtml() ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
            <?php endforeach; ?>
        </ol>
    </div>
<?php endif; ?>

We updated our file structure looks as follows:

app/code/Magetop/
  ├── Themes/
  │   ├── Block/
  │   │     ├── Products.php
  app/design/frontend/Magetop/
  ├── Default/
  │   ├── Magetop_themes/
  │   │     ├── templates/
  │   │     │   ├── product/       
  │   │     │   │   ├── bestseller.phtml

Good luck!

This is How to get product collection in Magento 2.

You can see the next post: Add Custom Category Attributes In Magento 2.

Follow us for more helpful tutorial!

We hope this is useful blog for you.

Thank you for reading!

3.9 7 votes
Article Rating

Adam Roger

CEO and Founder of Magetop. A friend, a husband and a dad of two children. Adam loves to travel to experience new cultures and discover what is happening with ecommerce all around the world.

Leave a Reply or put your Question here

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x