Skip to content

Magento 2 set product image role programmatically

Hello and this is my code:

$imgURL = 'path/to/my/image.png';
$fileSystem = $objectManager->create('MagentoFrameworkFilesystem');
$mediaPath = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath();

$product->addImageToMediaGallery($mediaPath.'catalog/product'.$data['thumbnail_image'],['thumbnail', 'swatch'], false, false);
$product->setThumbnail($mediaPath.'catalog/product'.$imgURL);
$product->save();

What I want to achive, is to assign programmatically an image and set it as a thumbnail.
The above code, uploads the image, but it’s role: the thumbnail and swatch are not selected. Not sure why ? See img:
enter image description here

Can you tell me what am i doing wrong ? thank you