如下代码可以放在产品详细页的任何位置,如view.phtml或者media.phtml中。本文放在相关产品的related.phtml,当后台设定的related product少于12个时,自动随机同一子分类下的其他产品补足12个改一改就可以改成随机显示某一个子分类下的产品,显示的数量,图片的大小在本代码中都是很容易改的。
app/code/core/Mage/Catalog/Block/Product/List/Related.php
//获取该产品的最底层分类,为获取其他产品 2012-4-27
public function getLastCat()
{
return end(Mage::registry('product')->getCategoryIds());
}
template/catalog/product/list/related.phtml
<!-- 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-->