Magento:如何以编程方式将基本图像设置为列表中的第一个图像

Hen*_*gen 7 image magento

问题

现在的情况

我遇到了第三方离子加载器编码的feedloader插件的问题,原始作者不再支持它(因为他们已经开始了)而不是花两周的时间从头开始写它,我已经决定修复导入运行后的问题.

兼容性

唯一的问题是:我想使用Mage库中的函数来编写它,而不是依赖于在Magento的下一次更新中可能会破坏的一些自定义查询,或者每当我在数据库中更改某些内容时(我只是想了解Magento的核心功能更好我猜)

问题诊断

除了设置基本图像(小图像和缩略图图像设置正确)之外,导入几乎所有内容都是正确的,如下面的屏幕截图所示:

第一个也是唯一一个图像尚未被选为默认基本图像

该图像缺少数据库中的实际记录..(因此很想用查询修复它,但我不会......我会继续寻找一个优雅的解决方案)

此外,函数$ product-> getMediaGalleryImages()不返回任何图像,因此我不能按照@SKV在Set Base Image上的建议使用解决方案..除非我做错了.

Mar*_*ius 25

$productId = 1;
//load the product
$product = Mage::getModel('catalog/product')->load($productId);
//get all images
$mediaGallery = $product->getMediaGallery();
//if there are images
if (isset($mediaGallery['images'])){
    //loop through the images
    foreach ($mediaGallery['images'] as $image){
        //set the first image as the base image
        Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array('image'=>$image['file']), 0);
        //stop
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*gen 6

这是我最终在'shell/fix_images.php'中使用的解决方案:

<?php
ini_set('display_errors','On');
ini_set('memory_limit','512M');
error_reporting(E_ALL);
require_once('abstract.php');

class Mage_Shell_Updater extends Mage_Shell_Abstract
{
    public function run()
    {
        $products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('is_imported', 1); // attribute added by importer
        $c=0;
        foreach($products as $p) {
            $pid = $p->getId();
            $product = Mage::getModel('catalog/product')->load($pid);
            $mediaGallery = $product->getMediaGallery();
            if (isset($mediaGallery['images'])){
                foreach ($mediaGallery['images'] as $image){
                    Mage::getSingleton('catalog/product_action')
                    ->updateAttributes(array($pid), array('image'=>$image['file']), 0);
                    $c++;
                    break;
                }
            }
        }
        echo($c . " product(s) updated.");
    }

}

$shell = new Mage_Shell_Updater();
$shell->run();
Run Code Online (Sandbox Code Playgroud)

如果有人应该使用它,请务必从您自己的Mage方法链中删除'addAttributeToFilter'.如果您要将其作为独立脚本运行(不首先禁用实时索引),请在运行开始时添加此代码():

    $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection(); 
    foreach ($pCollection as $process) {
        $process->setMode(Mage_Index_Model_Process::MODE_MANUAL)->save();
    }
Run Code Online (Sandbox Code Playgroud)

在run()结束时:

    foreach ($pCollection as $process) {
        $process->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->save();
    }
Run Code Online (Sandbox Code Playgroud)

此外,abstract.php来自Mage_Shell,通常位于Magento安装根目录的/ shell /目录中.