Cross-Sells – How to Get Random Cross Sell Products

cross-sellsrandom

This is the piece of code that generates the cross products:

<?php $_helper = $this->helper('catalog/output'); ?>
<?php 
    $_product = $this->getProduct(); 
   // echo get_class($this); 
?>

<?php if($_crossSellProducts = $_product->getCrossSellProducts()): ?>

    <div class="crosssell">
        <h2><?php echo $this->__('Suntem mandri sa va prezentam clientii TRENDfurniture:') ?></h2>

        <ul id="crosssell-products-list">
        <?php foreach ($_crossSellProducts as $_item): ?>

            <?php  
            $_item = Mage::getModel('catalog/product')->load($_item->getId()); 
            ?>
            <li class="item">
                <a class="product-image" href="<?php echo $_item->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_item->getName()) ?>">
                    <img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail'); ?>" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />
                </a>
            </li>

        <?php endforeach; ?>
        </ul>

        <script type="text/javascript">decorateList('crosssell-products-list', 'none-recursive')</script>
    </div>
<?php endif;?>

I tried to use:

 $_item ->getSelect()->order(new Zend_Db_Expr('RAND()'));                  
 $_item ->setPage(1, 4);

but with no result.This is the result of the get_class function : Mage_Catalog_Block_Product_View

Best Answer

create a function on view.php

    public function getCrosspro(){
        $product = $this->getProduct();
        /* @var $product Mage_Catalog_Model_Product */

        $itemCollection = $product->getCrossSellProductCollection()
            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
            ->setPositionOrder()
            ->addStoreFilter();

        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($itemCollection);
            $itemCollection->getSelect()->order(new Zend_Db_Expr('RAND()')); 
            $itemCollection->setPage(1, 4);
         $itemCollection->load();

        foreach ($itemCollection as $product) {
            $product->setDoNotUseCategoryId(true);
        };

return $itemCollection
}

and change:

<?php if($_crossSellProducts = $_product->getCrossSellProducts()): ?>

to

<?php if($_crossSellProducts = $this->getCrosspro()): ?>
Related Topic