Magento – Efficient way to get product URL and image

attributesce-1.9.0.1

While building an addition to a Magento webshop, I stumbled upon a couple of problems. In my pursuit to create code which is as fast as possible, I found myself unable to figure out two things.

My (relevant) code is the following:

$rc = Mage::getResourceSingleton('catalog/product');
$productName = $rc->getAttributeRawValue($productId, 'name', Mage::app()->getStore());
$productPrice = $rc->getAttributeRawValue($productId, 'price', Mage::app()->getStore());
$productImage = $rc->getAttributeRawValue($productId, 'image', Mage::app()->getStore());
$productUrl = $rc->getAttributeRawValue($productId, 'url_key', Mage::app()->getStore());

The two things I can't figure out are:

1) How do I retrieve the product URL? url_key doesn't always give the right URL, since not all webshops use canonical URL's, or have the category in the URL.

2) How can I get the product image with a set width/height, instead of the full image? The ->resize() function does not function in this case I recon (since it returns an URL). Added to that, is it possible to get the Base Image, Small Image and Thumbnail separately?

My main goal is to keep the code as fast as possible.
I only have a product id, since I loop through the children of a product. I do not wish to use ->load() since that takes way more loading time.

Best Answer

You can do it like this:

$smallImage = $rc->getAttributeRawValue($productId, 'small_image', Mage::app()->getStore());
$imageModel = Mage::getModel('catalog/product_image');
$imageModel->setDestinationSubdir('small_image');
$imageModel->setBaseFile($smallImage);
var_dump($imageModel->getUrl());

Analogously, you can also do it for "image" and "thumbnail".

Related Topic