1

i've followed the instructions to get random products generated on my homepage, placing {{block type="catalog/product_list_random" name="product_random" template="catalog/product/list_random.phtml"}} in the content section of the home page. problem is, i've been searching for a solution to limit the number of products displayed because the homepage is slow to load now. i have tried a few different solutions, here here here, etc, but i have a custom template installed and i don't understand where to put the code to limit it. here is the list_random.phtml code:

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>

<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div class="category-products"> <?php echo $this->getToolbarHtml() ?>
  <?php // List mode ?>
  <?php if($this->getMode()!='grid'): ?>
  <?php $_iterator = 0; ?>
  <ol class="products-list" id="products-list">
    <?php foreach ($_productCollection as $_product): ?>
    <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
      <?php // Product Image ?>
      <div class="list-inner"> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img class="pr-img" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(170); ?>" width="170" height="170" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /> </a><a href='<?php echo $this->getUrl('ajax/index/options',array('product_id'=>$_product->getId()));?>' data-fancybox-group="gallery" class='fancybox' id='fancybox<?php echo $_product->getId()?>' style=''><?php echo $this->__('Quick View') ?></a></div>
      <?php // Product description ?>
      <div class="product-shop">
        <div class="f-fix">
          <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
          <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
          <div class="desc std"> <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a> </div>
        <div class="wrapper">  <?php echo $this->getPriceHtml($_product, true) ?>
                 <div class="list-reviews"> <?php echo $this->getReviewsSummaryHtml($_product) ?> </div></div>
          <?php if($_product->isSaleable()): ?>
          <?php if ( !($_product->getTypeInstance(true)->hasRequiredOptions($_product) || $_product->isGrouped()) ) { ?>
          <div class="row-list">
            <p class="list-btn">
              <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocationAjax('<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
            </p>
            <span id='ajax_loader<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
            <?php } else { ?>
            <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button" onclick="showOptions('<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
            <span id='ajax_loader<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
            <?php }  ?>
            <?php else: ?>
            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
            <?php endif; ?>
            <ul class="add-to-links">
              <?php if ($this->helper('wishlist')->isAllow()) : ?>
              <li><a href="#" title="<?php echo $this->__('Add to Wishlist') ?>" onclick='ajaxWishlist("<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>","<?php echo $_product->getId()?>");return false;' class="link-wishlist tooltips"><?php echo $this->__('Add to Wishlist') ?></a></li>
              <?php endif; ?>
              <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
              <li><span class="separator">|</span> <a href="#" title="<?php echo $this->__('Add to Compare') ?>" onclick='ajaxCompare("<?php echo $_compareUrl ?>","<?php echo $_product->getId()?>");return false;' class="link-compare tooltips"><?php echo $this->__('Add to Compare') ?></a>
                <div id="results"></div>
              </li>
              <?php endif; ?>
            </ul>
            <span id='ajax_loading<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>

          </div>
        </div>

    </li>
    <?php endforeach; ?>
  </ol>
  <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
  <?php else: ?>
  <?php // Grid Mode ?>
  <?php $_collectionSize = $_productCollection->count() ?>
  <?php $_columnCount = $this->getColumnCount(); ?>
  <?php $i=0; foreach ($_productCollection as $_product): ?>
  <?php if ($i++%$_columnCount==0): ?>
  <ul class="products-grid">
    <?php endif ?>
    <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
            <h2 class="product-name product-name-height"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>

      <div class="grid-inner"> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img class="pr-img" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(203); ?>" width="203" height="203" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a> 
      <a href='<?php echo $this->getUrl('ajax/index/options',array('product_id'=>$_product->getId()));?>' data-fancybox-group="gallery" class='fancybox' id='fancybox<?php echo $_product->getId()?>' style=''><?php echo $this->__('Quick View') ?></a></div>

      <div class="product-box-2"> 
        <div class="desc std"> 
          <?php $small_description = strip_tags( $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description'));
             if (strlen($small_description) < '50') echo($small_description);
                else {
                  echo substr($small_description, 0, 55);
                  echo '...';
             }
          ?> 
      </div>
         <div class="product-atr-height">
             <?php echo $this->getPriceHtml($_product, true) ?> 
             <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
         </div>
        <div class="actions">
          <?php if($_product->isSaleable()): ?>
          <?php if ( !($_product->getTypeInstance(true)->hasRequiredOptions($_product) || $_product->isGrouped()) ) { ?>
          <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocationAjax('<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
          <span id='ajax_loader<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span> 
          <a href='<?php echo $this->getUrl('ajax/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style=''></a>
          <?php } else { ?>
          <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button" onclick="showOptions('<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
          <?php }  ?>
          <?php else: ?>
          <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
          <?php endif; ?>
          <ul class="add-to-links">
            <?php if ($this->helper('wishlist')->isAllow()) : ?>
            <li><a href="#" title="<?php echo $this->__('Add to Wishlist') ?>" onclick='ajaxWishlist("<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>","<?php echo $_product->getId()?>");return false;' class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
            <?php endif; ?>
            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
            <li><span class="separator">|</span> <a title="<?php echo $this->__('Add to Compare') ?>" href="#" onclick='ajaxCompare("<?php echo $_compareUrl ?>","<?php echo $_product->getId()?>");return false;' class="link-compare"><?php echo $this->__('Add to Compare') ?></a>
              <div id="results"></div>
            </li>
            <?php endif; ?>
          </ul>
        </div>
        <span id='ajax_loading<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span> </div>
    </li>
    <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
  </ul>
  <?php endif ?>
  <?php endforeach ?>
  <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
  <?php endif; ?>
  <div class="toolbar-bottom"> <?php echo $this->getToolbarHtml() ?> </div>
</div>
<?php endif; ?>

<script type="text/javascript">

jQuery(document).ready(function() {
 var vmcartck = jQuery('.top-link-cart');
 vmcartck.top = vmcartck.offset().top;
 vmcartck.left = vmcartck.offset().left;
 jQuery('.btn-cart').click(function() {
   var el = jQuery(this);
   var imgtodrag = jQuery('.rwerwe:first');
   if (!imgtodrag.length) {
    elparent = el.parent();
    while (!elparent.hasClass('item')) {
     elparent = elparent.parent();
    } 
    imgtodrag = elparent.find('img.pr-img');
   }
   if (imgtodrag.length) {
    var imgclone = imgtodrag.clone()
     .offset({ top: imgtodrag.offset().top, left: imgtodrag.offset().left })
  .css({'opacity': '0.7', 'position': 'absolute' , 'height':'150px' , 'width': '150px','z-index': '1000'})
     .appendTo(jQuery('body'))
     .animate({
      'top': vmcartck.top+10,
      'left': vmcartck.left+30,
      'width':55,
      'height':55
     },1000, 'linear');
    imgclone.animate({
     'width': 0,
     'height': 0
    });
   }
 });  
    var maxHeight = 0;
    function setHeight(column) {
        column = jQuery(column);
        column.each(function() {       
            if(jQuery(this).height() > maxHeight) {
                maxHeight = jQuery(this).height();;
            }
        });
        column.height(maxHeight);
    }
    setHeight('.product-name-height');
    setHeight('.product-atr-height');

});

</script>
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function(){
        jQuery('.fancybox').fancybox(
            {
               hideOnContentClick : true,
               width:800,
               autoDimensions: true,
               type : 'iframe',
               showTitle: true,
               scrolling: 'no',
               onComplete: function(){
                jQuery('#fancybox-frame').load(function() { // wait for frame to load and then gets it's height
                    jQuery('#fancybox-content').height(jQuery(this).contents().find('body').height()+30);
                    jQuery.fancybox.resize();
                 });

               }
            }
        );
    });
    function showOptions(id){
        jQuery('#fancybox'+id).trigger('click');
    }
    function setAjaxData(data,iframe){
        if(data.status == 'ERROR'){
            alert(data.message);
        }else{
            if(jQuery('.block-cart')){
                jQuery('.block-cart').replaceWith(data.sidebar);
            }
                                    if(jQuery('.block-cart-header')){
                jQuery('.block-cart-header').replaceWith(data.sidebar_header);
            }
            if(jQuery('.header .links')){
                jQuery('.header .links').replaceWith(data.toplink);
            }


        }
    }
    function setLocationAjax(url,id){
        url += 'isAjax/1';
        url = url.replace("checkout/cart","ajax/index");
        jQuery('#ajax_loader'+id).show();
        try {
            jQuery.ajax( {
                url : url,
                dataType : 'json',
                success : function(data) {
                    jQuery('#ajax_loader'+id).hide();
                    if(data.status == 'ERROR'){
                                    jQuery('body').append('<div class="alert"></div>');
                        jQuery('.alert').slideDown(400);
                            jQuery('.alert').html(data.message).append('<button></button>');
                jQuery('button').click(function () {
                jQuery('.alert').slideUp(400);
                 });    
                            jQuery('.block-cart-header .cart-content').hide();
            jQuery('.block-cart-header  .amount-2 a').hover(function(){
                jQuery('.block-cart-header .cart-content').stop(true, true).slideDown(400);
            },function(){
                jQuery('.block-cart-header .cart-content').stop(true, true).delay(400).slideUp(300);
            }); 
                    jQuery('.alert').slideDown('400',function(){
                                        setTimeout(function(){
                                            jQuery('.alert').slideUp('400',function(){jQuery(this).slideUp(400)});
                                        },7000)
                                     });
        }else{

                        jQuery('body').append('<div class="alert" ></div>');
                        jQuery('.alert').slideDown(400);
                jQuery('.alert').html(data.message).append('<button></button>');
                jQuery('.alert').html(data.message).wrapInner('<a href="<?php echo $this->getUrl('checkout/cart') ?>"></a>');
                jQuery('button').click(function () {
                jQuery('.alert').slideUp(400);
                 });    
                    jQuery('.alert').slideDown('400',function(){
                                        setTimeout(function(){
                                            jQuery('.alert').slideUp('400',function(){jQuery(this).slideUp(400)});
                                        },7000)
                                     });
                                                jQuery('.block-cart-header .cart-content').hide();
            jQuery('.block-cart-header  .amount-2 a').hover(function(){
                jQuery('.block-cart-header .cart-content').stop(true, true).slideDown(400);
            },function(){
                jQuery('.block-cart-header .cart-content').stop(true, true).delay(400).slideUp(300);
            }); 
            if(jQuery('.block-cart')){
                jQuery('.block-cart').replaceWith(data.sidebar);
            }
                        if(jQuery('.block-cart-header')){
                jQuery('.block-cart-header').replaceWith(data.sidebar_header);
            }
            if(jQuery('.header .links')){
                jQuery('.header .links').replaceWith(data.toplink);
            }

        }

                }
            });
        } catch (e) {
        }
    }
    jQuery(".add-to-links li a.tooltips").easyTooltip();
        jQuery(".products-grid .add-to-links .link-wishlist").easyTooltip();
        jQuery(".products-grid .add-to-links .link-compare ").easyTooltip();



</script>

i understand there are a lot of posts regarding limiting the numbers, but i don't fully understand the edits required, or the ones i tried didnt work. if anyone can offer some help, i'd appreciate it. im using magento 1.9.0.1

  • or, a dirty way to do it, how would i use php to pick a random set of numbers for item numbers, and display them on the home page? – Tim Jun 4 '14 at 20:54
  • That's not as dirty as you might think, if done right. The catalog/product_list_random block with its ORDER BY RAND() approach is very unperformant. Please see magento.stackexchange.com/questions/3429/… – Fabian Schmengler Oct 5 '15 at 7:40
2

An elegant solution will be to change Mage_Catalog_Block_Product_List_Random.php file

$numProducts = $this->getNumProducts() ? $this->getNumProducts() : 0;
$collection->setPage(1, $numProducts);

Change the $numProducts to the number of products you need.

If you do not want to override the core class you can always check for the initiate and increment a counter for each loop iteration and just break the loop when the counter reaches desired value:

$counter = 0;

<?php foreach ($_productCollection as $_product): ?>
$counter++;
if($counter == 5) break;
<?php endforeach;?>
| improve this answer | |
  • I made the change to the random.php file, but it didnt have an effect. cleared cache, reindexed, etc. still tried to list all 14000 products. i've removed the toolbar from the page so that you dont see that, but it still runs through the routine of building the random listing, so the webpage is slow to load. for the counter loop, would i need to add the code to the homepage? – Tim Jul 14 '14 at 13:57
0

num_products should get passed as NumProducts in the Random Block, so the widget directive exists:

{{block type="catalog/product_list_random" name="product_random" num_products="8" template="catalog/product/list_random.phtml"}}

Source: http://svn.magentocommerce.com/source/branches/1.8/app/code/core/Mage/Catalog/Block/Product/List/Random.php

Also, if you are having performance issues you may have other unrelated issues, unless after this change was made things became slower.

| improve this answer | |
  • usign num_products didnt help. – Tim Jul 14 '14 at 13:58

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.