Search code examples
magentomagento-1.9

how to assign random product positions in Magento category?


I have the following issue in Magento 1.9: there are categories with a lot of products in them and the default sort order is by position and all product position in Magento backend is 1. So what happens is that when you open a category on the frontend a lot of similar products show first followed by another set of similar type of products. I want to randomize their positions somehow (by a script or anything else) so that different kind of products show mixed together.

For example I have categories wine, champagne and whisky and products in them and I also have category birthday products that includes products from these categories. And when the category is opened on the frontend first a lot of whisky products are shown then a lot of wine ... etc I want them mixed. Thanks in advance for any help!


Solution

  • You can do as below :

    First get the category :

    $category = Mage::getModel('catalog/category')
    ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
    ->load($categoryId);
    

    Then its product positions :

    $products = $category->getProductsPosition();
    

    This will be an array organized like this :

    product_id_1 => position_1
    product_id_1 => position_2
    

    So foreach one of those products just set a random position (here between 0 and 9999) :

    foreach($products as $productId => $position ){
        $products[$productId] = '' . rand(0,9999);
    }
    

    And finally save :

    $category->setPostedProducts($products);
    $category->save();
    

    Here is below a script that you could put in /shell magento directory :

    <?php
    require_once './abstract.php';
    
    class RandomCategoryOrder extends Mage_Shell_Abstract {    
        private $_categoryId = 188;
    
        public function run(){
            $category = Mage::getModel('catalog/category')
            ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
            ->load($this->_categoryId);
    
            $products = $category->getProductsPosition();
    
            foreach($products as $productId => $position ){
                $products[$productId] = '' . rand(0,9999);
            }
    
            $category->setPostedProducts($products);
    
            try{
                $category->save();
            }catch(Exception $e){
                echo $e->getMessage();
            }
        }    
    
    }
    $randowCategoryOrder = new RandomCategoryOrder();
    $randowCategoryOrder->run();