Magento – How to set thumbnail image programmatically in Magento 2

imagemagento2products

How can I set main product image as thumbnail image programmatically in Magento 2?

Scenario:

I have a loop running trough all products and each product has a main image, only some products have not defined an image for thumbnail. So I want to set the main image also as the product thumbnail for each product.

Best Answer

Thank you for the reply.

I already found the answer by myself and I will share it below.

foreach ($products as $product){

    $smallImage = $product->getSmallImage();
    $imagePath  = '/catalog/product' . $product->getImage();

    if( $smallImage == 'no_selection' ){
        echo 'FIXING ' . $imagePath . "\r\n";
        $product->addImageToMediaGallery( $imagePath, array( 'small_image' ), false, false );
        $product->save();
    }
}

But still, I'm curious to know what are the Boolean variables are here.

$product->addImageToMediaGallery( $imagePath, array( 'small_image' ), false, false );
Related Topic