简体   繁体   中英

Grabbing a custom product image label in Magento?

I have a block on my front page that is grabbing the two newest products with a custom product image called image_feature_front_right .

I use this code as the query:

$_helper = $this->helper('catalog/output');
$_productCollection = Mage::getModel("catalog/product")->getCollection();
$_productCollection->addAttributeToSelect('*');
$_productCollection->addAttributeToFilter("image_feature_front_right", array("notnull" => 1));
$_productCollection->addAttributeToFilter("image_feature_front_right", array("neq" => 'no_selection'));
$_productCollection->addAttributeToSort('updated_at', 'DESC');
$_productCollection->setPageSize(2);

I am able to get:

  • the image: echo $this->helper('catalog/image')->init($_product, 'image_feature_front_right')->directResize(230,315,4)
  • the product url: echo $_product->getProductUrl()
  • the product name: $this->stripTags($_product->getName(), null, true)

The only thing I am unable to get is the custom images label. I have tried echo $this->getImageLabel($_product, 'image_feature_front_right') , but that seems to do nothing.

Can anyone point me in the right direction?

Thanks!

Tre

I imagine this is some sort of magento bug. The issue seems to be that the Magento core is not setting the custom_image_label attribute. Whereas for the default built-in images [image, small_image, thumbnail_image] it does set these attributes - so you could do something like:

$_product->getData('small_image_label');

If you look at Mage_Catalog_Block_Product_Abstract::getImageLabel() it just appends '_label' to the $mediaAttributeCode that you pass in as the 2nd param and calls $_product->getData() .

If you call $_product->getData('media_gallery'); you'll see the custom image label is available. It's just nested in an array. So use this function:

function getImageLabel($_product, $key) {
    $gallery = $_product->getData('media_gallery');
    $file = $_product->getData($key);
    if ($file && $gallery && array_key_exists('images', $gallery)) {    
        foreach ($gallery['images'] as $image) {
            if ($image['file'] == $file)
                return $image['label'];
        }
    }
    return '';
}

It'd be prudent to extend the Magento core code (Ideally Mage_Catalog_Block_Product_Abstract , but I don't think Magento lets you override Abstract classes), but if you need a quick hack - just stick this function in your phtml file then call:

<?php echo getImageLabel($_product, 'image_feature_front_right')?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM