The code below works for products that have images, but for products that don't have images, the placeholder small image doesn't show.
echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage());
The code that affects what you want to do is
//file: app/code/core/Mag/Catalog/Helper/Image.php
//class: Mage_Catalog_Helper_Image
/**
* Return Image URL
*
* @return string
*/
public function __toString()
{
try {
//...
} catch (Exception $e) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
The interesting line is
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
So in your code you need to test the return value of $_product->getSmallImage()
and if it is false or null use Mage::getDesign()->getSkinUrl($this->getPlaceholder());
instead.
You might want to inspect $_product->getSmallImage()
to see what it returns when no value is set.
Oh, and I just checked: getPlaceholder()
is a function not a magic getter. This is the function:
public function getPlaceholder()
{
if (!$this->_placeholder) {
$attr = $this->_getModel()->getDestinationSubdir();
$this->_placeholder = 'images/catalog/product/placeholder/'.$attr.'.jpg';
}
return $this->_placeholder;
}
So you will have to unravel some $this
(hint $this->_getModel()
is Mage::getModel('catalog/product_image')
)
or to cut a long story short just fall back to the default:
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
in your phtml file if $_product->getSmallImage()
doesn't exist.
Update following your comment:
Specifcically in the .phtml
file that you are using to generate the HTML that displays the small image you could write:
$testSmallImageExists = $_product->getSmallImage();
if($testSmallImageExists)
{
echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage());
}
else
{
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
}
Or just simply use
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
I'm sure that is the standard Magento way.
app/code/core/Mage/Catalog/Helper/Image.php
– fresher