Tuesday, May 29, 2012

Magento: Random Product Lists


There are two unused product list blocks in Magento which can be very useful if you push a few buttons, edit few layouts ..
1. Promotion
Block located in app\code\core\Mage\Catalog\Block\Product\List\Promotion.php
This is basically built in featured product functionality. It reacts to “promotion” attribute which needs to be created, so let’s click
Catalog->Attributes->Manage Attributes->Create New Attribute
Attribute Code: promotion
Scope: Global
Catalog Input Type for Store Owner: Yes/No
promotion-and-random-1
Label: Promotion (second tab)
Other params can be left alone, but it’s up to you of course. I also labeled it Promotion just for this article.
Now we need to add created attribute to attribute set, so navigate to
Catalog->Attributes->Manage Attribute Sets
select attribute set you’re using and drag promotion to General group for example.
promotion-and-random-2
Now when you’re editing your products, there is new “Promotion” option under General tab.
promotion-and-random-3
Products on which you select Yes will be shown on promotion block which can be displayed through layouts with
<block type="catalog/product_list_promotion" name="product_promotion" template="catalog/product/list.phtml"/>
or as cms content with
{{block type='catalog/product_list_promotion' template='catalog/product/list.phtml'}}
This attribute should really be included in default attribute set or in Magento sample data.
2. Random
Block located in app\code\core\Mage\Catalog\Block\Product\List\Random.php
This block loads random product collection from current store.
The fastest way to display it would also be something like
<block type="catalog/product_list_random" name="product_random" template="catalog/product/list.phtml"/>
since it also extends product_list block, however, since it is random product listing, that toolbar has no purpose here, so create phtml that will suit your shop needs, based on catalog/product/list.phtml. For example, i’m using similar Random block to display random products in sidebar.

Method 2

<?php

//below code to written in file which extends the product block
$collection = Mage::getResourceModel('catalog/product_collection');
        Mage::getModel('catalog/layer')->prepareProductCollection($collection);
        $collection->getSelect()->order('rand()');
        $collection->addStoreFilter();
        $this->setProductCollection($collection);
        return parent::_beforeToHtml();     

?>
  //below code to written in template file

        if (($_products = $this->getProductCollection())):
        echo $_product->getSku();
        endif;
You can extend the script further as per your requirement. This is a basic way of displaying random products in a page from the product catalog.

Method 3
Place the respective codes given below for displaying new/ most viewed/ random products list in Home page or any other CMS pages in Magento.
New Product
{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_new" template="catalog/product/new.phtml"}}
Most viewed product
{{block type="mostviewed/list" name="home.mostviewed.list" alias="product_homepage" template="catalog/product/list.phtml"}}
To display products from a particular category. Please replace <Category-ID> with the category id
{{block type="catalog/product_list" category_id="<Category-ID>" template="catalog/product/list.phtml"}}
To display random products
{{block type="catalog/product_list_random" template="catalog/product/list.phtml"}}




Method 4

Today i’ll show you How to create a Random Products in your Magento Home page.

Create the Home Products file

In my theme I created a copy of the list.phtml called home_list.phtml
/app/design/frontend/base/theme156/template/catalog/product

Show the file in the Home Page

Now we need to show our new file in the Home Page.
Go to your Admin panel -> CMS -> Pages
You should have a page called something like Home. Open it and paste the following code:
{{block type="catalog/product_list" category_id="36" template="catalog/product/home_list.phtml"}}
NOTE: please notice the category_id. It will force to show a certain category. In my case a special one called Home Products.

Shuffle it

The code is quite simple. We need to add the shuffle function after getting all the products.
Look for the getItems() function and past it below.
    <?php $_items = $_productCollection->getItems(); 
        shuffle($_items); ?>

Break on 3

I added a counter to break the foreach. Something like:
// Show 3 items
$max_items = 3;
$personal_count = 1;
And then at the end:
  if($personal_count == $max_items){break;}
  else{$personal_count++;}

Full Code

Here’s my full code of the home_list.phtml. It will depend on your theme but the suffle part should be the same.
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   design_blank
 * @package    Mage
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

?>
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */

?>
<?php $userIsloggedIn = Mage::getSingleton('customer/session')->isLoggedIn(); ?>
<?php $_productCollection=$this->getLoadedProductCollection() ?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div style="clear:both;">&nbsp;</div>
<div class="category-products" style="border:none !important;">
   
    <div class="page-indent">    
        <?php // List mode ?>
        <?php if($this->getMode()!='grid'): ?>
        <?php $_iterator = 0; ?>
        <ol class="products-list" id="products-list">
        <?php $list_item=1; foreach ($_productCollection as $_product): ?>
            <li class="item<?php if($list_item==1){echo ' first ';} ?><?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                <?php // Product Image ?>
                <class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                    <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a>
    
                <?php // Product description ?>
                <div class="product-shop">
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName())?></a></h3>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <p><button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button></p>
                    <?php else: ?>
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>

                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>                    
                </div>
                <div class="clear"></div>
                <div class="desc std">
                    <?php echo nl2br($_product->getShortDescription()) ?>
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->__('Learn More') ?></a>
                </div>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
            </li>
        <?php $list_item++; endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
    
        <?php else: ?>
    
        <?php // Grid Mode ?>
    
        <?php $_collectionSize = $_productCollection->count() ?>
        <table class="products-grid" id="products-grid-table">
        <?php $_columnCount = 3/*$this->getColumnCount()*/; ?>
        
         <?php 
            $_items = $_productCollection->getItems(); 
            shuffle($_items); 
        ?>
        
        < ? 
            // Show 3 items
            $max_items = 3;
            $personal_count = 1;
        ?>
        <?php $i=0; foreach ($_items as $_product): ?>
        
            <?php if ($i++%$_columnCount==0): ?>
            <tr>
            <?php endif ?>
                <td>
                    <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
                    <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                        <img src="<?php echo $this-/>helper('catalog/image')->init($_product, 'small_image')->resize(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
                    </a>                    
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <button type="button" class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <?php else: ?>
                        
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>
                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>
                  
                </td>
            <?php if ($i%$_columnCount==0 && $i!=$_collectionSize): ?>
            </tr>
            <?php endif ?>
            < ? 
               if($personal_count == $max_items){break;}
               else{$personal_count++;}
            ?>
            <?php endforeach ?>
            <?php for($i;$i%$_columnCount!=0;$i++): ?>
                  <td class="empty">&nbsp;</td>
            <?php endfor ?>
            <?php if ($i%$_columnCount==0): ?>
            
            <?php endif ?>
        </table>
        <script type="text/javascript">decorateTable('products-grid-table')</script>
        <?php endif; ?>        
    </div>
  
</div>
<?php endif; ?>


Method 5

To display random products on home page in Magento Theme you need to follow the below give steps:-
Step 1. Create a new file called random.phtml atapp/design/frontend/default/Your_Theme/template/catalog/random.phtml with the following given code:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php 
$chosen_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$_productCollection = $this->getLoadedProductCollection();
$number_of_products = $this->getNumProducts();
if (sizeof($_productCollection) < $number_of_products) {
 $number_of_products = sizeof($_productCollection);
}
$displayed_products = array();
foreach ($_productCollection as $_product) {
 $displayed_products[] = $_product;
}
$random_products = array();
if (sizeof($_productCollection) > 1) {
 $random_products = array_rand($displayed_products, $number_of_products);
} else {
 $random_products = array('0');
}
?>
<?php if(!$_productCollection->getSize()):?>
<div class="note-msg">
    <?=$this->__('There are no products matching the selection.')?>
</div>
<?php else:?>
 
<div class="main-binder">
  <div class="cms-box">
  <div class="category-title">
      <h2>Random Products</h2>
  </div> 
  <div class="category-products">
    <table id="products-grid-table" class="products-grid">
 <?php 
 $k=0;
 for ($i=0; $i < $number_of_products; $i++): ?>
 <?php if ($k == 0) { ?>
   <tr class="first odd">
  <?php } if($k==3) { $k=0;  ?> 
   </tr><tr class="first odd even">
  <?php } ?>
         <td id="td_<?php echo ($k+1); ?>" <?php if($k==3){ ?>class="last"<? } ?> >
  <div class="cms-box">
              <div id="cont_<?php echo ($k+1); ?>">
     <div class="product-name-block">                 
      <?php
      $pname=$this->htmlEscape($displayed_products[$random_products[$i]]->getName());
      ?>
      <h3 class="product-name">      
      <a href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>" title="<?php echo $pname; ?>">
                    <?php if(strlen($pname) > 28) {echo substr($pname,0,25)."...";}else {echo $pname;}?>
                    </a></h3>
                </div>
                <div class="image-box">     
    <a class="product-image" href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>"> <img src="<?php echo $this->helper('catalog/image')->init($displayed_products[$random_products[$i]], 'small_image')->resize(140);?>" alt="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>" title="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>"/> </a> 
    </div>
 
    <div class="cms-price-box" style=" text-align:center;">
     <span class="regular-price" id="product-price-37">      
      <span class="price" ><?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->
     getCurrentCurrencyCode())->getSymbol().$displayed_products[$random_products[$i]]->getPrice(); ?></span>
     </span>                      
    </div>
    <div class="button-row" style="text-align:center;">
       <button onclick="setLocation('<?php echo $displayed_products[$random_products[$i]]->getProductUrl();?>')" class="button" type="button"><span><span><span>Details</span></span></span></button>                               
     <button onclick="setLocation('<?php echo $this->getUrl('')."/checkout/cart/add?product=".$displayed_products[$random_products[$i]]->getId()."&qty=1"  ?>')" class="button"><span><?php echo $this->__('Add to Cart') ?></span></button>
    </div>
              </div>
        </div></td> 
 
<?php $k++; ?>
<?php endfor;?>
</tr>
      </table>     
    </div>
  </div>
</div>  
<?php endif;?>
Step 2. Now put this line where you want to show the best selling products.
1
2
3
<p>{{block type="catalog/product_list" category_id="3" num_products="8" template="catalog/random.phtml"}}</p>
 
 Note: Category Id will be specific to your Store.


By PHP with 1 comment

1 comments:

Great method you have highlighted.

Also, Highlighting the best selling products will be a good deal to go and increase sales via magento ecommerce website.

Post a Comment

    • Popular
    • Categories
    • Archives