以下代碼能夠放在產品詳細頁的任何位置,如view.phtml或者media.phtml中。本文放在相關產品的related.phtml,當後臺設定的related product少於12個時,自動隨機同一子分類下的其餘產品補足12個改一改就能夠改爲隨機顯示某一個子分類下的產品,顯示的數量,圖片的大小在本代碼中都是很容易改的。php
app/code/core/Mage/Catalog/Block/Product/List/Related.phphtml
//獲取該產品的最底層分類,爲獲取其餘產品 2012-4-27 public function getLastCat() { return end(Mage::registry('product')->getCategoryIds()); }
template/catalog/product/list/related.phtmlapp
<!-- BOF 當關聯產品小於12個,自動調用同子分類的產品補足12個 byPaul 2012-4-26--> <!--forshow other product--> <?php $categories = $this->getLastCat(); $result = array(); $category = Mage::getModel('catalog/category'); $category->load($categories); $collection = $category->getProductCollection(); foreach ($collection as $product) { $result[] = $product->getId(); } ?> <?php /* $categories = $this->getCats(); $result = array(); foreach($categories as $cat_id) { $category = Mage::getModel('catalog/category'); $category->load($cat_id); $collection = $category->getProductCollection(); foreach ($collection as $product) { $result[] = $product->getId(); } }*/ ?> <?php /* 隨機全部產品的 * $result = array(); $products = Mage::getModel('catalog/product')->getCollection(); $prodIds=$products->getAllIds(); $result = $prodIds;*/ ?> <?php if(sizeof($result) > $rest)//大於12減去related的數目 { $ourneed= array_rand($result,$rest); foreach($ourneed as $cc) { $thisproduct= Mage::getModel('catalog/product')->load($result[$cc]); ?> <li class="item"> <div class="product"><a href="<?php echo $thisproduct->getProductUrl(); ?>" title="<?php echo $this->htmlEscape($thisproduct->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($thisproduct, 'thumbnail')->resize(90) ?>" width="90" height="90" alt="<?php echo $this->htmlEscape($thisproduct->getName()) ?>" /></a> <div class="product-infos"> <p class="product-name"><a href="<?php echo $thisproduct->getProductUrl() ?>"><?php echo $this->htmlEscape($thisproduct->getName()) ?></a></p> <?php echo $this->getPriceHtml($thisproduct, true, '-related') ?></div> </div> </li> <?php } ?> <?php }else { foreach($result as $cc) { $thisproduct= Mage::getModel('catalog/product')->load($cc); ?> <li class="item"> <div class="product"><a href="<?php echo $thisproduct->getProductUrl(); ?>" title="<?php echo $this->htmlEscape($thisproduct->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($thisproduct, 'thumbnail')->resize(90) ?>" width="90" height="90" alt="<?php echo $this->htmlEscape($thisproduct->getName()) ?>" /></a> <div class="product-infos"> <p class="product-name"><a href="<?php echo $thisproduct->getProductUrl() ?>"><?php echo $this->htmlEscape($thisproduct->getName()) ?></a></p> <?php echo $this->getPriceHtml($thisproduct, true, '-related') ?></div> </div> </li> <?php } } ?> <!--forshow other product--> <!-- EOF 當關聯產品小於12個,自動調用同分類的產品補足12個 byPaul 2012-4-26-->