好的 - 我无法使用 MAGMI 找到允许我导入类别图像的解决方案。相反,我找到了一个 PHP 解决方案:
- 遍历所有 Magento 产品类别
- 保存当前类别中产品的随机(或定义)图像
- 使用步骤 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”语句将随机选择一个类别产品。需要注意的是,这会大大增加脚本的执行时间。