Magento 2.4.2

I'm creating products programmatically with this code:


namespace Vendor\Base\Helper\Product;

use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Validation\ValidationException;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;

class CreateProduct
    protected $productFactory;
    protected $productRepository;
    protected $_sourceItemsSaveInterface;
    protected $_sourceItemFactory;

    public function __construct(
        ProductFactory $productFactory,
        ProductRepository $productRepository,
        SourceItemsSaveInterface $sourceItemsSaveInterface,
        SourceItemInterfaceFactory $sourceItemFactory

    ) {
        $this->productFactory = $productFactory;
        $this->productRepository = $productRepository;
        $this->_sourceItemsSaveInterface = $sourceItemsSaveInterface;
        $this->_sourceItemFactory = $sourceItemFactory;

    public function createProduct()

        if ($this->doesProductExist('totallyUniqueSku')) {
            return 'totallyUniqueSku';
        if (!$productDetails->isValid()) {
            return false;

        $product = $this->productFactory->create();

        $product->setData('attribute_set_id', 4);//default = 4
        $product->setData('website_ids', [1]);
        $product->setData('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $product->setData('visibility', 1);//1 = not vis individually
        $product->setData('category_ids', [1,2,3]);//just an example of the ids. this works fine.
        $product->setData('price', '123.00');
        $product->setData('type_id', 'simple'));
        $product->setData('tax_class_id', 1);
        $product->setData('description', 'super cool description');
        $product->setData('short_description', 'super cool short desc');
        $product->setData('stock_data', [  // set product quantity
                'use_config_manage_stock' => 0,
                'manage_stock' => 1,
                'is_in_stock' => 1,
                'qty' => 1
        $url = $product->formatUrlKey('TotallyUniqueURLKey');
        //-------------- Code in question --------------

        $images = ['relative/path/to/image.jpeg', 'relative/path/to/image2.jpeg'];
        if ($images && (is_array($images) || is_object($images))) {
            foreach ($images as $image) {
                if ($i < 1) {
                    $mediaAttribute = ['image', 'small_image', 'thumbnail'];
                } else {
                    $mediaAttribute = null;

                $product->addImageToMediaGallery($image, $mediaAttribute);
        //-------------- End Code in question --------------

        try {

            return $product->getSku();
        } catch (CouldNotSaveException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #3');
        } catch (InputException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #4');
        } catch (StateException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #5');
        return true;

    protected function doesProductExist($sku): bool
        try {
            $product = $this->productRepository->get($sku);
            if ($product) {
                return true;
            return false;
        } catch (NoSuchEntityException $e) {
            return false;



    public function log($in)
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/debug.log');
        $logger = new \Zend\Log\Logger();

The product is created successfully, the issue is that the image does not show on the product page. There are no images on the product page, but if I search for the product, the search results show the image correctly. The images are also displayed correctly when editing the product from the admin backend.

Some of the product data in the example code might be off slightly, but the code relating to the images is correct.

Why doesn't the image show up on the product page?

  • Run command line php bin/magento indexer:reindex Jul 20 '21 at 4:43
  • @LitExtensionMagentoMigration this does not fix the issue
    – Hunter
    Jul 22 '21 at 16:42
  • Make sure the /media directory is in your Apache web server's group. Magento also needs to be able to write to this directory, so you can run this command to set those permissions: sudo chmod -R 775 /path/to/magento/media Jul 31 '21 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.