I am adding images to the products from a folder programmatically using addImageToMediaGallery function. below is my controller code
<?php
namespace Kammalou\AddMissingImages\Controller\Missing;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Images extends \Magento\Framework\App\Action\Action
{
protected $pageFactory;
public function __construct(Context $context, PageFactory $pageFactory)
{
$this->pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
var_dump(__METHOD__);
$page_object = $this->pageFactory->create();
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()->addAttributeToSelect('*')->load();
foreach ($collection as $product){
$productId = $product->getId() ; // Id of product
$product = $obj->create('Magento\Catalog\Model\Product')->load($productId);
$image = $product->getImage();
if($image =='' || $image=='no_selection' ){
// echo 'Name = '.$product->getName().'<br>';
$imagePath = "/var/www/vhosts/m2atimedev/httpdocs/var/inriver/pics/".$product->getName().".jpg";
// path of the image
//echo $imagePath;exit;
if(file_exists($imagePath)){
//Remove Images From Product
$productRepository = $obj->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
if($existingMediaGalleryEntries){
foreach ($existingMediaGalleryEntries as $key => $entry) {
unset($existingMediaGalleryEntries[$key]);
}
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);
// Adding Image to product
$product = $obj->create('Magento\Catalog\Model\Product')->load($productId);
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
}
//echo 'image = '.$product->getImage().'<br>';
}
}
return $page_object;
}
}
The code is working very fine. but the problem is when images are set as thumbnail only for default magento scope. In the store scope image is showing but not selected as thumbnails.
when i change scope, the base small thumbnail image does not show selected.
As a result in the frontend the images are not showing with the products on category and search results page.
If we click on products with missing images, than on the product page images is showing correctly.
How to show images with products on category page programmatically. Right now i have to go to backend, select product, change scope to store and set base, small and thumbnail image.