在Magento中抓取自定义产品图片标签?

时间:2012-05-11 00:05:24

标签: php image magento label

我的首页上有一个块,它使用名为image_feature_front_right的自定义产品图片抓取两个最新产品。

我使用此代码作为查询:

$_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);

我能得到:

  • 图片:echo $this->helper('catalog/image')->init($_product, 'image_feature_front_right')->directResize(230,315,4)
  • 产品网址:echo $_product->getProductUrl()
  • 产品名称:$this->stripTags($_product->getName(), null, true)

我唯一无法获得的是自定义图像标签。我试过了echo $this->getImageLabel($_product, 'image_feature_front_right'),但这似乎什么也没做。

有人能指出我正确的方向吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

我想这是某种magento bug。问题似乎是Magento核心没有设置custom_image_label属性。而对于默认的内置图像[image,small_image,thumbnail_image],它确实设置了这些属性 - 所以你可以这样做:

$_product->getData('small_image_label');

如果您查看Mage_Catalog_Block_Product_Abstract::getImageLabel(),只需将“_label”附加到您作为第2个参数传入的$mediaAttributeCode并调用$_product->getData()

如果您致电$_product->getData('media_gallery');,您会看到自定义图片标签可用。它只是嵌套在一个数组中。所以使用这个功能:

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 '';
}

谨慎扩展Magento核心代码(理想情况下为Mage_Catalog_Block_Product_Abstract,但我认为Magento不允许您覆盖抽象类),但如果您需要快速破解 - 只需将此功能添加到您的phtml文件然后调用:

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