5 Programming Questions and Answers Regarding Magento Product Sorting - Part 2

April 5, 2017,
5 Programming Questions and Answers Regarding Magento Product Sorting - Part 2

Nowadays it is quite simple to resolve issues regarding programming and coding as on the internet there is a huge community of developers which you can find and follow on various web development forums. However, this is not an easy task for a new programmer who is not familiar with the search engine queries because it is an art to use search engine i.e. Google.

It is not possible to enlist all the programming queries in one single blog; however, we update our blog with fresh content on the regular basis. Here in this blog post, we are going to continue our series of questions and answers regarding Product sorting in Magento from our previous blog post on the same topic.
Useful Resources
Magento Sort Products Extension 1. Sort by new 2. Bestsellers 3. Most viewed products 4. Top-rated products 5.  Popularity In the second episode, we will cover next five most frequently asked questions regarding Magento product sorting. Remember, these are the questions selected by FMEAddons from the top community and hence we are not direct representatives of this. Have a look on the questions selected for this week’s blog post.

Question No.1

User have three subcategories under a main category i.e.
Root Cat
  Sub Cat 1
  Sub Cat 2
  Sub Cat 3
The requirements are to display products from each category in ascending order. Means Cat 1 product should come first and so on. If the order of categories changed, the product order should change accordingly. How to achieve this goal in Magento? Use have also tried
$productCollection = Mage::getResourceModel('catalog/product_collection');
But it doesn't work for him.

Answer:

You can achieve this objective by using the addCategoryFilter() function. For example
$categories = Mage::getModel('catalog/category')->getCollection();
foreach ($categories as $category) {
    echo $category->getId() . ':' . PHP_EOL;
    $products = Mage::getModel('catalog/product')->getCollection()
        ->addCategoryFilter($category);
    foreach ($products as $product) {
        // Do something
        echo '  ' . $product->getSku() . PHP_EOL;
    }
}

Question No.2

User has created a new template in Magento, now want to display the featured products on the front page and also want to control the order of products. The current code is:
php
    $_productCollection = $this->getLoadedProductCollection();
?>
User has tried the below piece of code and believe that it will work but the result was the same as above.
php
    $_productCollection = $this->getLoadedProductCollection()->addAttributeToSort('name', 'ASC');
?>

Answer:

You can use the code given below this will work for you
$collection = Mage::getModel('catalog/product')
             ->getCollection()
             ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_ASC);
for descending order sorting
$collection = Mage::getModel('catalog/product')
              ->getCollection()
              ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_DESC);
for sorting products with its category
$collection = Mage::getModel('catalog/category')->load($categoryId)
             ->getProductCollection()
             ->addAttributeToSort('name', Varien_Data_Collection::SORT_ORDER_ASC);

Question No.3

The user is unable to sort the product by price, currently, sort by name works fine. User have tried
System->Cache Management->Layered Navigation Indices->Refresh now.
The current Magento version is 1.3.2.4

Answer:

Seems there might a bug in the Magento version. Update addAttributeToSort function ofMage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection  class. Comment out below section of code
//        if ($attribute == 'price' && $storeId != 0) {
//            $websiteId = Mage::app()->getStore()->getWebsiteId();
//            $customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId();
//
//            if ($this->isEnabledFlat()) {
//                $priceColumn = 'e.display_price_group_' . $customerGroup;
//                $this->getSelect()->order("{$priceColumn} {$dir}");
//            }
//            else {
//                $priceAttributeId = $this->getAttribute('price')->getId();
//
//                $entityCondition = '_price_order_table.entity_id = e.entity_id';
//                $storeCondition = $this->getConnection()->quoteInto(
//                    '_price_order_table.website_id = ?',
//                    $websiteId
//                );
//                $groupCondition = $this->getConnection()->quoteInto(
//                    '_price_order_table.customer_group_id = ?',
//                    $customerGroup
//                );
//                $attributeCondition = $this->getConnection()->quoteInto(
//                    '_price_order_table.attribute_id = ?',
//                    $priceAttributeId
//                );
//
//                $this->getSelect()->joinLeft(
//                    array('_price_order_table'=>$this->getTable('catalogindex/price')),
//                    "{$entityCondition} AND {$storeCondition} AND {$groupCondition} AND {$attributeCondition}",
//                    array()
//                );
//                $this->getSelect()->order('_price_order_table.value ' . $dir);
//
//                /**
//                 * Distinct we are using for remove duplicates of products which have
//                 * several rows in price index (like grouped products)
//                 */
//                $this->getSelect()->distinct(true);
//            }
//
//            return $this;
//        }

Question No.4

How to sort products by position in Magento?

Answer:

If you want to sort products by position in the category, you can use the following code.
//Load the category model

 $category = Mage::getModel('catalog/category')->load($category_id)
             ->getProductCollection()
             ->addAttributeToSort('position', 'ASC');

$products_list = $category->getData();

Question No.5

how to move "Sort by" option box from its original position to the right. It is a simple question but will be difficult for new users. The part of CSS file is
/* Sorter */
.sorter { font-size:11px; padding:1px 8px; }
.sorter .view-mode { float:left; margin:0; }
.sorter .sort-by { float: right; }
.sorter .sort-by label { vertical-align:middle; }
.sorter .sort-by select { padding:0 ; margin: 1px; vertical-align:middle; }
.sorter .link-feed {}

Answer:

You just need to add below line in your style.css and you will be all done.
.pager .sort-by { float: right;  margin-left: 15px;}

Download Magento Sort products Extension 

sort-products