Tuesday 24 June 2014

Magento Create Limited & Random Product List.

In my case i have create featured product list with product 10 and it display randomaly.
Please copy past following code in your collection block file.


protected function _getProductCollection()
{
        if (is_null($this->_productCollection)) {
            $collection = Mage::getModel('catalog/product')->getCollection();
            $collection
            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
            ->addMinimalPrice()
            ->addFinalPrice()
                    ->addAttributeToFilter('featured_product', 1)
            ->addTaxPercents();
            $collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
            $collection->setPage(1, 10)->load();

            Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
            Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
            $this->_productCollection = $collection;

        }
        return $this->_productCollection;
}

Magento Sort Category(Navigation) By Name or Alphabatically.

To sort Top Menu Categories and its Sub-Categoiries alphabetically,

Copy app/code/core/Mage/Catalog/Block/Navigation.php to app/code/local/Mage/Catalog/Block/Navigation.php OR you can override the same file in your local

public function toLinearArray($collection)
{
        $array = array();
        foreach ($collection as $item) $array[] = $item;
        return $array;
}

protected function _sortCategoriesByName($cat1, $cat2)
{
       return strcasecmp($cat1->getName(), $cat2->getName());
}

In Navigation.php edit the function _renderCategoryMenuItemHtml(), add the following 2 lines before the code $hasChildren = ($children && $childrenCount);

$children = $this->toLinearArray($children);
usort($children, array($this, '_sortCategoriesByName'));

If you need to sort Parent Categories too, use below code before your foreach loop when you display category list

<?php $helper = Mage::helper('catalog/category') ?>
<?php $categories = $helper->getStoreCategories(); ?>
               
<?php $children = $this->toLinearArray($categories);
usort($children, array($this, '_sortCategoriesByName'));?>
   
<?php foreach ($children as $_category): ?>
<?php echo $this->drawItem($_category) ?>
<?php endforeach ?>