Last active
March 17, 2021 22:09
-
-
Save ivandoric/83562fc7644a5d5fd416 to your computer and use it in GitHub Desktop.
magento: Check if product is new in product listing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$newFromDate = Mage::getModel('catalog/product')->load($_product->getID())->getNewsFromDate(); | |
$newToDate = Mage::getModel('catalog/product')->load($_product->getID())->getNewsToDate(); | |
$now = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT); | |
if(($newFromDate < $now && $newFromDate != NULL) && ($newToDate > $now || $newToDate == "")){ | |
echo "New Product"; | |
} | |
?> |
You absolutely must NOT convert and validate dates manually, because this can cause timezone issues. Magento has built-in method isStoreDateInInterval()
in Mage_Core_Model_Locale
class. So you should create helper method which can look like this
function isProductNew(Mage_Catalog_Model_Product $product)
{
$newsFromDate = $product->getNewsFromDate();
$newsToDate = $product->getNewsToDate();
if (!$newsFromDate && !$newToDate) {
return false;
}
return Mage::app()->getLocale()
->isStoreDateInInterval($product->getStoreId(), $newsFromDate, $newsToDate);
}
More details you can find here http://m-grater.info/all/check-product-is-new/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to limit the number of database queries, load the product only once.
I ran into performance problems using a theme where the product was loaded 4 times to get new et special dates. On listing pages, where 24 products were displayed, it ended with near 2 thousands database queries. Removing the load calls, it drop down to hundred queries.