2013-04-24 49 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'語句將隨機選擇一個類別產品。應該指出的是,這將大大增加腳本執行時間。