Set Base Image Programmatically

妖精的绣舞 提交于 2019-12-04 12:39:11

Hello You can do as follows :

$image =$imagePath."image.png";
$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
if(is_file($image))
{
    $product->addImageToMediaGallery($image, array ('image', 'small_image', 'thumbnail'), false, false);
}

i.e you need to first set the media gallery, P.S This is a necessary step.

then add all images to gallery using addImageToMediaGallery where 'image' ref to 'base_image'

i.e in above example we are setting image.png to base_image, small_image and thumbnail image in a single call.

hope this helps you.

I've achieved the same result by using:

$product->setSmallImage($path)
    ->setThumbnail($path)
    ->setImage($path)
    ->save();

Works better for the case where your media gallery has one or more pictures in it.

I'm doing

$product->load();
$gallery = $product->getMediaGalleryImages();

$paths = array();
foreach ($gallery as $image) {
    $paths[] = $image->getFile();
}
sort($paths);

$path = array_shift($paths);
try {
    $product->setSmallImage($path)
        ->setThumbnail($path)
        ->setImage($path)
        ->save();
} catch (Exception $e) {
    echo $e->getMessage();
}

Which gets all the product images, sort's them by file name and sets the first to the product primary image. As I ran a import and added all my pictures, but didn't set the primary image.

To grab a set or "broken" products I used:

    $collection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToFilter('small_image', array('eq' => ''));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!