1

I am trying to create a product programmatically in magento 2.1.3. I have 2 storeviews, be and fr. when I create product, product URLs(in URL rewrite) are only created for 'be' storeview, not created for 'fr' storeview. Can anyone Please help me to solve this issue??

This is my code

<?php

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Setup\CategorySetup;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Framework\App\Bootstrap;


include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$ob = $bootstrap->getObjectManager();

$state = $ob->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

/** @var $installer CategorySetup */
$installer = $ob->create(CategorySetup::class);

/** @var ProductRepositoryInterface $productRepository */
$productRepository = $ob->create(ProductRepositoryInterface::class);

/** @var AttributeOptionInterface[] $options */
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');

$p = $ob->get(\Magento\Catalog\Api\Data\ProductInterface::class);

$p->setSku('simple_sku');
$p->setName('simple_name');
$p->setPrice(100);
$p->setAttributeSetId($attributeSetId);
$p->setTypeId('simple');
$p->setVisibility(1);
$p->setWeight(1);
$p->setStoreIds(array(2,3)); // 2 and 3 are my store ids
$p->setCategoryIds(array(1,3,5));
$p->setStockData(array(
    'use_config_manage_stock' => 0,
    'manage_stock' => 1,
    'min_sale_qty' => 1,
    'max_sale_qty' => 2,
    'is_in_stock' => 1,
    'qty' => 5 
    )
);
$p = $productRepository->save($p);

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.