Add images to product description content programatically in Magento2
-
19-03-2021 - |
题
I want to add images to my product description content block but I don't want these specific images to appear in the product gallery ('image', 'small_image', 'thumbnail').
To add regular images I do it the following way:
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
For my description I could do something like that:
$descr = "<img src='".$media_path."' />";
$product->setDescription($desc);
And get the path of images using:
$productimages = $product->getMediaGalleryImages();
Is there any other type of image I could use to achieve my goal ? Or what way should I use to upload these image and reuse them in my product description ?
解决方案
Please add this to your Standalone script.
foreach (new DirectoryIterator('./descr_images') as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
$imagePath = $fileInfo->getFilename(); // path of the image
$filesystemIo = $objectManager->create('\Magento\Framework\Filesystem\Io\File');
$filePath = ''; // Path of your local directory image
$copyFileFullPath = $mediaPath . $imagePath;
$filesystemIo->cp($filePath, $copyFileFullPath);
$mediaPath = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$descImage = "<img src='" . $mediaPath . $imagePath . "'/>";
$productDesc = $product->getDescription();
$product->setDescription($productDesc . $descImage);
$product->save();
}
Clear cache and then check it.