The question:
I want need to show New label on new product in product list page.
Help me for the achieve this task.
How can it will Show in magento2 ?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
Propably the best option is to add new helper with following code:
<?php
namespace VendorModuleHelper;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoCatalogModelProduct as ModelProduct;
use MagentoStoreModelStore;
use MagentoFrameworkStdlibDateTimeTimezoneInterface;
class HelperName extends MagentoFrameworkUrlHelperData
{
/**
* @var TimezoneInterface
*/
protected $localeDate;
public function __construct(
MagentoFrameworkAppHelperContext $context,
TimezoneInterface $localeDate
) {
$this->localeDate = $localeDate;
parent::__construct($context);
}
public function isProductNew(ModelProduct $product)
{
$newsFromDate = $product->getNewsFromDate();
$newsToDate = $product->getNewsToDate();
if (!$newsFromDate && !$newsToDate) {
return false;
}
return $this->localeDate->isScopeDateInInterval(
$product->getStore(),
$newsFromDate,
$newsToDate
);
}
}
Then in .phtml file use this:
$helper = $this->helper('VendorModuleHelperHelperName');
and in products foreach
:
<?php if($helper->isProductNew($_product)): ?>
Your label code here
<?php endif; ?>
Method 2
Create helper and add code.
<?php
namespace VendorModuleHelper;
use MagentoFrameworkStdlibDateTimeTimezoneInterface;
class Newlabel extends MagentoFrameworkUrlHelperData
{
/**
* @var TimezoneInterface
*/
protected $localeDate;
public function __construct(
TimezoneInterface $localeDate
) {
$this->localeDate = $localeDate;
}
public function isProductNew($product)
{
$newsFromDate = $product->getNewsFromDate();
$newsToDate = $product->getNewsToDate();
if (!$newsFromDate && !$newsToDate) {
return false;
}
return $this->localeDate->isScopeDateInInterval(
$product->getStore(),
$newsFromDate,
$newsToDate
);
}
}
Add below code to list.phtml file (in foreach)
<?php $helper = $this->helper('VendorModuleHelperNewlabel'); ?>
<?php if($helper->isProductNew($_product)): ?>
<div class="new-lable">
<?php echo __('New'); ?>
</div>
<?php endif; ?>
And finally it will show NEW label in product list page. Working Great.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0