2013-04-24 45 views
2

我已经将400多个类别导入到Magento安装中。 每个类别有多个产品,但没有分类图像。批量更新Magento类别图像

我已经编写了一个脚本来遍历每个类别,并返回当前类别中第一个产品的图像的URL。

下一步是将返回的产品图像设置为其父级类别的图像。

我的第一种方法是使用类别ID和类别图像URL格式化CSV以供MAGMI使用,但是在检查文档http://sourceforge.net/apps/mediawiki/magmi/index.php?title=Import_categories后,我一直无法找到关于导入类别图像的任何信息。 MAGMI有可能吗?

如果不符合上述要求,我的下一个方法是使用PHP以编程方式设置类别图像。 我找到了以下片段,我打算修改如果MAGMI方法失败。任何人都可以确认setThumbnail方法的$ image参数是否接受完全限定的URL,还是仅仅引用本地文件路径?

$category = Mage::getModel('catalog/category')->load($cat); 
$category->setImage($image); 
$category->save(); 

非常感谢!

回答

3

好的 - 我无法找到使用MAGMI的解决方案,它允许我导入类别图像。 相反,我来到了一个PHP的解决方案:

  1. 遍历所有的Magento产品分类
  2. 从产品保存当前类别
  3. 更新当前类别的图像与内的随机(或规定)图像在步骤2中保存的图像。

这里是整个代码,其中一些可能在处理类似任务时会发现有用。

<?php 

/* require the necessary magento classes */ 

require_once 'app/Mage.php'; 
Mage::app('default'); // Default or your store view name. 

/* construct a category tree object to traverse */ 

$category = Mage::getModel('catalog/category'); 
$tree = $category->getTreeModel(); 
$tree->load(); 

$ids = $tree->getCollection()->getAllIds(); 
$arr = array(); 

/* loop through each category id */ 

if ($ids){ 
    foreach ($ids as $id){ 
     getImageForCategory($id); 
     updateCategoryThumbnail($id); 
    } 
} 

function getImageForCategory($id){ 

     $images = array(); 

     $catId=$id; // put your category ID in here 
     $products = Mage::getModel('catalog/product')->getCollection() 
     ->addAttributeToSelect('image') 
     ->addCategoryFilter(Mage::getModel('catalog/category')->load($catId)); 

     Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($products); // Only select products that are salable 

     $products->load(); 


     foreach($products as $product){ 
      $images[] = $product->getImageUrl(); 

      /* remove the following break if you want to use a random image, otherwise the image of the first product will be used. Using random images will cause the execution time to increase dramatically. */ 
      break; 
     } 


     if (sizeof($images) > 1) { 
     $random_image = array_rand($images, 1); 
     } else { 
     $random_image = 0; 
     } 

     if($images[$random_image]){ 
      saveImageFromURL($images[$random_image],$id);  
     } 

    } 

function updateCategoryThumbnail($cat){ 

    $image = $cat . ".jpg"; 

    $catc = Mage::getModel('catalog/category')->load($cat); 
    $catc->setImage($image); // /media/catalog/category 
    $catc->save(); 
} 

function saveImageFromURL($imgUrl,$cat){ 


    $fout = fopen('/var/www/vhosts/your-site-folder.com/httpdocs/media/catalog/category/' . $cat . '.jpg', 'w'); 
    $fin = fopen($imgUrl, "rb"); 
    while (!feof($fin)) { 
     $buffer= fread($fin, 32*1024); 
     fwrite($fout,$buffer); 
    } 
    fclose($fin); 
    fclose($fout); 
} 

?>

确保有在所述saveImageFromURL()函数所使用的类别的图像文件夹足够写权限。

如上所述,从getImageForCategory()中删除'break'语句将随机选择一个类别产品。应该指出的是,这将大大增加脚本执行时间。