Skip to content

Instantly share code, notes, and snippets.

@ivandoric
Last active March 17, 2021 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivandoric/83562fc7644a5d5fd416 to your computer and use it in GitHub Desktop.
Save ivandoric/83562fc7644a5d5fd416 to your computer and use it in GitHub Desktop.
magento: Check if product is new in product listing
<?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";
}
?>
@julien-maitan
Copy link

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.

<?php
$_product = Mage::getModel('catalog/product')->load($_product->getID()); // This line can be removed depending were you are
$newFromDate = $_product->getNewsFromDate();
$newToDate = $_product->getNewsToDate();
$now = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
if(($newFromDate < $now && $newFromDate != NULL) && ($newToDate > $now || $newToDate == "")){
echo "New Product";
}

@obukhow
Copy link

obukhow commented Sep 20, 2015

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