2

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 ?

14
  • In which file you are adding this code, Controller or Block? Nov 14, 2019 at 5:20
  • Standalone script Nov 14, 2019 at 5:21
  • See my answer and then check it and let me know if it is working properly. Nov 14, 2019 at 5:29
  • This is not the requirement. The question is about adding the images to Magento programmatically, and being able to use them in product descr, but not having them appearing in the product images. The part you describe in your solution I can do already, but how to add images the right way and get their path ? Nov 14, 2019 at 5:31
  • You want to add all product images to description? Nov 14, 2019 at 5:42

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.