Product Image default position not changed in magento
-
12-12-2019 - |
Question
I tried to change the default position for each image in product.
$products = mage::getModel('catalog/product')->load(1311);
$attributes = $products->getTypeInstance(true)->getSetAttributes($products);
$gallery = $attributes['media_gallery'];
$images = $products->getMediaGalleryImages();
foreach ($images as $image) {
$attributes['media_gallery']->getBackend()->updateImage($products, $image->getFile(), $data=array('label'=>'good','position'=>10,'position_default'=>11));
}
$products->getResource()->saveAttribute($products, 'media_gallery');
$products->save();
From the above code, the image position is changed but image position default is not changed.
[value_id] => 25865
[file] => /2/0/20_Tulips.jpg
[label] => good
[position] => 10
[disabled] => 0
[label_default] =>
[position_default]=>
La solution
Try the below code to change the default position for one image.
$product = Mage::getModel('catalog/product')->load(120);
$sku = $product->getSku();
$media = Mage::getModel('catalog/product_attribute_media_api');
$absolute_path = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$f.DS.$s.DS.$filename;
$position = 0;
if (file_exists($absolute_path)) {
$pathInfo = pathinfo($absolute_path);
switch($pathInfo['extension']){
case 'png':
$mimeType = 'image/png';
break;
case 'jpg':
$mimeType = 'image/jpeg';
break;
case 'gif':
$mimeType = 'image/gif';
break;
}
$types = ($position == 0) ? array('image', 'small_image', 'thumbnail') : array();
$newImage = array(
'file' => array(
'content' => base64_encode($absolute_path),
'mime' => $mimeType,
'name' => basename($absolute_path),
),
'label' => 'whatever', // change this.
'position' => $position,
'types' => $types,
'exclude' => 0,
);
$media->create($sku, $newImage);
// OR (if you would rather use the product entity ID):
// $media->create($productId, $newImage, null, 'id');
} else {
echo "image not found";
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange