2

In Magento default catalog category product sort by position.

I would like to add custom product position base on country in Magento CMS category.

In the frontend product sort depending on the visitor country. If there is no catalog country position available in the CMS then it will sort by default position.

Example : I have some categories and their products. Each category products popularity/position is different depending on countries(USA Position and India Position). So I need add two more position column (uas_position india_postion) and sort depending on set position.

How I will achieve this functionality?

Note: Using IP2Location I get visitor country.

0

Here I assume you have 2 catalog_product attributes.

  • usa_position
  • india_position

which have used_for_sort_by and used_in_product_listing is set to 1. This is important because without this Magento product collection sort won't work.

What you need to do is observer to the event catalog_block_product_list_collection and your observer should look like this:

<?php
class Namespace_Module_Model_Observer
{
    const COUNTRY_US = 'US';
    const COUNTRY_INDIA = 'IN';
    const DEFAULT_SORT_DIRECTION = 'ASC';

    protected $_indiaPosAttribute = 'india_position';
    protected $_usPosAttribute    = 'usa_position';

    public function changeSortOrderProductCollection(Varien_Event_Observer $observer)
    {
        $sortby = '';
        $collection = $observer->getEvent()->getCollection();

        //checks country and pick appropirate position attribute
        if ($this->visitorCountry() == self::COUNTRY_US) {
            $sortby = $this->_usPosAttribute;

        } elseif ($this->visitorCountry() == self::COUNTRY_US) {
            $sortby = $this->_indiaPosAttribute;
        }

        //remove all previous sorts and apply our own sort
        if ($sortby != '') {
            $collection->getSelect()->reset('sort')
                ->setOrder($sortby, self::DEFAULT_SORT_DIRECTION);
        }

        //use default positon sort
        $collection->addAttributeToSort('position', self::DEFAULT_SORT_DIRECTION);

        return $this;
    }

    protected function visitorCountry()
    {
        //here should come your country identification logic
    }
}

Basically what we are doing here is, we applying our custom sort based on the country (if it is available).

Hope that helps you out.


[This answer is a part of #mageStackDay5. It is an event conducted by Magento Community members as part of increasing the question-answer ratio. For more information http://www.magestackday.com/]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.