2
votes

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());

2
did you placed the code in below file to work for products which have images ? app/code/core/Mage/Catalog/Helper/Image.phpfresher

2 Answers

4
votes
<?php 
   // get image full url

       echo $imageUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product' . $_product->getImage();

    // get image using custom size with url 

        echo $imageCacheUrl = Mage::helper('catalog/image')->init($_product, 'image')->resize(135,135); 
    ?>
0
votes

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.