how I can get a list of newly created products? I want to display in frontend the latest added products.
4 Answers
I guess that you want a new product collection depends created_at
field.
So, you have to create a block class at your module and at that block class, you have to create a product collection and sort by DESCENDING created_at
ORDER.
I have create a block class at here depends on the structure of Magento\Catalog\Block\Product\NewProduct
and that block class must be extended
Magento\Catalog\Block\Product\AbstractProduct
implement agento\Framework\DataObject\IdentityInterface
At _getProductCollection()
,I build that a product collection and sort by created_at desc.
<?php
namespace {VendorName}\Catalog\Block\Product;
use Magento\Customer\Model\Context as CustomerContext;
/**
* New products block
*
* @SuppressWarnings(PHPMD.LongVariable)
*/
class NewProduct extends \Magento\Catalog\Block\Product\AbstractProduct implements
\Magento\Framework\DataObject\IdentityInterface
{
/**
* Default value for products count that will be shown
*/
const DEFAULT_PRODUCTS_COUNT = 10;
/**
* Products count
*
* @var int
*/
protected $_productsCount;
/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;
/**
* Catalog product visibility
*
* @var \Magento\Catalog\Model\Product\Visibility
*/
protected $_catalogProductVisibility;
/**
* Product collection factory
*
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
/**
* @param Context $context
* @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
* @param \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility
* @param \Magento\Framework\App\Http\Context $httpContext
* @param array $data
*/
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
\Magento\Framework\App\Http\Context $httpContext,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->httpContext = $httpContext;
parent::__construct(
$context,
$data
);
}
/**
* Initialize block's cache
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->addColumnCountLayoutDepend('empty', 6)
->addColumnCountLayoutDepend('1column', 5)
->addColumnCountLayoutDepend('2columns-left', 4)
->addColumnCountLayoutDepend('2columns-right', 4)
->addColumnCountLayoutDepend('3columns', 3);
$this->addData(
['cache_lifetime' => 86400, 'cache_tags' => [\Magento\Catalog\Model\Product::CACHE_TAG]]
);
}
/**
* Get Key pieces for caching block content
*
* @return array
*/
public function getCacheKeyInfo()
{
return [
'CATALOG_PRODUCT_CREATED_BY_DESC',
$this->_storeManager->getStore()->getId(),
$this->_design->getDesignTheme()->getId(),
$this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
'template' => $this->getTemplate(),
$this->getProductsCount()
];
}
/**
* Prepare and return product collection
*
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection|Object|\Magento\Framework\Data\Collection
*/
protected function _getProductCollection()
{
/** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
$collection = $this->_productCollectionFactory->create();
$collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
$collection = $this->_addProductAttributesAndPrices(
$collection
)->addStoreFilter()->addAttributeToSort(
'created_at',
'desc'
)->setPageSize(
$this->getProductsCount()
)->setCurPage(
1
);
return $collection;
}
/**
* Prepare collection with new products
*
* @return \Magento\Framework\View\Element\AbstractBlock
*/
protected function _beforeToHtml()
{
$this->setProductCollection($this->_getProductCollection());
return parent::_beforeToHtml();
}
/**
* Set how much product should be displayed at once.
*
* @param int $count
* @return $this
*/
public function setProductsCount($count)
{
$this->_productsCount = $count;
return $this;
}
/**
* Get how much products should be displayed at once.
*
* @return int
*/
public function getProductsCount()
{
if (null === $this->_productsCount) {
$this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
}
return $this->_productsCount;
}
/**
* Return identifiers for produced content
*
* @return array
*/
public function getIdentities()
{
return [\Magento\Catalog\Model\Product::CACHE_TAG];
}
}
Call this Block class from cms_index_index.xml
layout file
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content.aside">
<block class="{VendorName}\{ModuleName}\Block\Product\NewProduct" name="catalog.product.related" template="Magento_Catalog::product/list/items.phtml">
<arguments>
<argument name="type" xsi:type="string">new</argument>
</arguments>
<block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="new.product.addto" as="addto">
<block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
name="new.product.addto.compare" as="compare"
template="Magento_Catalog::product/list/addto/compare.phtml"/>
</block>
</block>
</referenceContainer>
</body>
</page>
Try Below way.
Create your block file and add below code
<?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
protected $_productVisibility;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory;
$this->_productVisibility = $productVisibility;
parent::__construct($context, $data);
}
public function getProductCollection() {
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
// filter current website products
$collection->addWebsiteFilter();
$collection->addAttributeToSort('entity_id','desc');
// filter current store products
$collection->addStoreFilter();
// set visibility filter
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
// fetching only 5 products
$collection->setPageSize(5);
return $collection;
}
}
and your phtml file call yor block
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
echo $product->getId() . '<br />';
echo $product->getName() . '<br />';
}
using object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
// filter current website products
$collection->addWebsiteFilter();
$collection->addAttributeToSort('entity_id','desc');
// filter current store products
$collection->addStoreFilter();
// set visibility filter
$collection->setVisibility($objectManager->get('\Magento\Catalog\Model\Product\Visibility')->getVisibleInSiteIds());
// fetching only 5 products
$collection->setPageSize(5);
foreach ($productCollection as $product) {
echo $product->getId() . '<br />';
echo $product->getName() . '<br />';
}
If you want it can be done via admin :
Create a Cms Block , and as a content , inser a widget :
- Add widget type : Catalog Product List
- Set Number of Products to Display: (usually is used 4 )
- Tempate : Products Grid Template
- For your request to be the New Products : You can either use a
condition to set up a category for the new products.
Or you dont wont the condition , insert the widget of New Products directly:
Attach the cms block you created into your homepage .
To add a list of new products on the home page of your website you can follow the below instructions
1st Method
- Go to the following location
Admin (backend) > Content > Elements > Widgets
- Click on the Add Widgets.
- In
Settings
section select Type => Catalog new Product List & select your theme & press to continue. - In
Storefront Properties
section give a title to your widgets & select your store. - In the Layout Updates click on the Add Layout Updates button.
- Select Specified Page into the Display on Section. -In the new generated section select your page & the area where you want to load the widgets.
- In the
Widgets
options section select New Products in the Display Type - Select the other options as per your requirement like Display Page Control, Number of Products to Display, Cache Lifetime.
- Click on the save button.
2nd Method
- Go to below location
Admin (backend) > Content > Elements > Pages
- Select your Page(Home Page in your case).
- In the content section click on the Show/Hide Editor.
- Paste the below code at your desired place
Code:
{{widget type="Magento\Catalog\Block\Product\Widget\NewWidget" display_type="new_products" show_pager="1" products_per_page="5" products_count="10" template="product/widget/new/content/new_grid.phtml" page_var_name="pmbfrt" type_name="Catalog New Products List"}}