Set Base Image Programmatically

2019-04-12 11:08发布

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.

Below you can see an overview of my goal.

I am trying to sell Similar product in my magento for this i wrote some code that every thing is working fine..

But i have only one problem with images..

that is I am getting all images of current product but the base image is not selected, How can i set the very first image as base image Programmatically.

Any ideas ?

2条回答
一纸荒年 Trace。
2楼-- · 2019-04-12 11:51

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' => ''));
查看更多
你好瞎i
3楼-- · 2019-04-12 12:12

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.

查看更多
登录 后发表回答