【问题标题】:Bulk update of Magento Category ImagesMagento 类别图像的批量更新
【发布时间】:2013-04-17 22:12:03
【问题描述】:
我已将 400 多个类别导入到 Magento 安装中。
每个类别都有多个产品,但没有类别图像。
我编写了一个脚本来遍历每个类别并返回当前类别中第一个产品图像的 URL。
下一步是将返回的产品图片设置为其父类别的图片。
我的第一种方法是使用类别 ID 和类别图像 URL 格式化 CSV 以与 MAGMI 一起使用,但是在检查http://sourceforge.net/apps/mediawiki/magmi/index.php?title=Import_categories 的文档后,我无法找到有关导入类别图像的任何信息。 MAGMI 可以做到这一点吗?
如果上述情况失败,我的下一个方法是使用 PHP 以编程方式设置类别图像。
我找到了以下 sn-p,如果 MAGMI 方法失败,我打算对其进行修改。任何人都可以确认 setThumbnail 方法的 $image 参数是否将接受完全限定的 URL,或者这是否仅指本地文件路径?
$category = Mage::getModel('catalog/category')->load($cat);
$category->setImage($image);
$category->save();
非常感谢所有输入!
【问题讨论】:
标签:
image
magento
import
thumbnails
categories
【解决方案1】:
好的 - 我无法使用 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”语句将随机选择一个类别产品。需要注意的是,这会大大增加脚本的执行时间。