Connect with us

Blog

Magento 2 : Programmatically creating Magento product

mm

Published

on

In a development process, you need some testing data you can use. Magento supplies you with it’s default Sample Data that contains products.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create(‘\Magento\Catalog\Model\Product’);
$product->setSku(‘mysku’); // Set your sku here
$product->setName(‘Sample Product’); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product
$product->setTaxClassId(0); // Tax class id
$product->setTypeId(‘simple’); // type of product
$product->setPrice(100); // price of product
$product->setStockData(
array(
‘use_config_manage_stock’ => 0,
‘manage_stock’ => 1,
‘is_in_stock’ => 1,
‘qty’ => 999999999
)
);
$product->save();

## Add custom options to the product this can be applied for other product type such as Configurable Product, Virtual, Downloadable Product, etc.

// Adding Custom option to product
$options = array(
array(
“sort_order”    => 1,
“title”         => “Custom Option 1”,
“price_type”    => “fixed”,
“price”         => “1000”,
“type”          => “field”,
“is_require”   => 0
),
array(
“sort_order”    => 2,
“title”         => “Custom Option 2”,
“price_type”    => “fixed”,
“price”         => “2000”,
“type”          => “field”,
“is_require”   => 0
)
);
foreach ($options as $arrayOption) {
$product->setHasOptions(1);
$product->getResource()->save($product);
$option = $objectManager->create(‘\Magento\Catalog\Model\Product\Option’)
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($arrayOption);
$option->save();
$product->addOption($option);
}

To create simple, configurable, downloadable products as the following:
•    Simple product: you need to pass the weight setting.
•    Configurable product: it is required to combine between associated products current product.
•    Downloadable product: it is required to insert the download link into the current product.

$productId = 1; // Configurable Product Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create(‘Magento\Catalog\Model\Product’)->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create(‘Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute’);
$position = 0;
$attributes = array(13, 15); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array(2,6); //Product Ids Of Associated Products
foreach ($attributes as $attributeId) {
$data = array(‘attribute_id’ => $attributeId, ‘product_id’ => $productId, ‘position’ => $position);
$position++;
$attributeModel->setData($data)->save();
}
$product->setTypeId(“configurable”); // Setting Product Type As Configurable
$product->setAffectConfigurableProductAttributes(4);
$objectManager->create(‘Magento\ConfigurableProduct\Model\Product\Type\Configurable’)->setUsedProductAttributeIds($attributes, $product);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->save();

Simple Product with custom attributes:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
$product = $objectManager->create(‘\Magento\Catalog\Model\Product’);
$product->setSku(‘sku’); // Set your sku here
$product->setName(‘Simple Product’); // Name of Product
$product->setAttributeSetId(4); // Attribute set id
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight(10); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setTaxClassId(0); // Tax class id
$product->setTypeId(‘simple’); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice(100); // price of product
$product->setStockData(
array(
‘use_config_manage_stock’ => 0,
‘manage_stock’ => 1,
‘is_in_stock’ => 1,
‘qty’ => 999999999
)
);
$product->save();

// Adding Image to product
$imagePath = “simple.jpg”; // path of the image
$product->addImageToMediaGallery($imagePath, array(‘image’, ‘small_image’, ‘thumbnail’), false, false);
$product->save();

// Adding Custom option to product
$options = array(
array(
“sort_order”    => 1,
“title”         => “Custom Option 1”,
“price_type”    => “fixed”,
“price”         => “1000”,
“type”          => “field”,
“is_require”   => 0
),
array(
“sort_order”    => 2,
“title”         => “Custom Option 2”,
“price_type”    => “fixed”,
“price”         => “2000”,
“type”          => “field”,
“is_require”   => 0
)
);
foreach ($options as $arrayOption) {
$product->setHasOptions(1);
$product->getResource()->save($product);
$option = $objectManager->create(‘\Magento\Catalog\Model\Product\Option’)
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($arrayOption);
$option->save();
$product->addOption($option);
}

Create a configurable Magento 2 product:

$configurable_product = $this->_objectManager->create(‘\Magento\Catalog\Model\Product’);
$configurable_product->setSku(‘testconfigurable’);
$configurable_product->setName(‘test configurable name’);
$configurable_product->setAttributeSetId(4);
$configurable_product->setStatus(1);
$configurable_product->setTypeId(‘configurable’);
$configurable_product->setPrice(110);
$configurable_product->setWebsiteIds(array(1));
$configurable_product->setCategoryIds(array(31));
$configurable_product->setStockData(array(
‘use_config_manage_stock’ => 0, //’Use config settings’ checkbox
‘manage_stock’ => 1, //manage stock
‘is_in_stock’ => 1, //Stock Availability
)
);

$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(152),$configurable_product); //attribute ID of attribute ‘size_general’ in my store
$configurableAttributesData = $configurable_product->getTypeInstance()->getConfigurableAttributesAsArray($configurable_product);
$configurable_product->setCanSaveConfigurableAttributes(true);
$configurable_product->setConfigurableAttributesData($configurableAttributesData);
$configurableProductsData = array();
$configurableProductsData[$simple_product_id] = array( //[$simple_product_id] = id of a simple product associated with this configurable
‘0’ => array(
‘label’ => ‘S’, //attribute label
‘attribute_id’ => ‘152’, //attribute ID of attribute ‘size_general’ in my store
‘value_index’ => ‘193’, //value of ‘S’ index of the attribute ‘size_general’
‘is_percent’    => 0,
‘pricing_value’ => ‘100’,
)
);
$configurable_product->setConfigurableProductsData($configurableProductsData);
$configurable_product->save();
echo “conf product id: “.$configurable_product->getId().”\n”;

Also Read :   Kylie Jenner & Travis Scott: The holy Commitment they have crazy

Hi, Thank you for reading my article. I am Victor, a professional blogger from Jaipur, India.I started webetutorial for blogging & sharing solution for developer questions, and now it’s empowering globally by helping them to make money.I am writing about starting & managing a blogs, WordPress, Magento, Social Media, SEO, Marketing, making money online, Investment, Finance, Gadgets, Fitness and more.

Continue Reading
Advertisement
1 Comment

1 Comment

  1. mm

    suthanalley67

    February 1, 2018 at 8:39 am

    That’s really an interesting tutorial creating products programmatically.

Leave a Reply

Your email address will not be published. Required fields are marked *

one + 7 =

Blog

Ways to Increase Comments on Your Blog

mm

Published

on

Ways to Increase Comments on Your Blog

Everyone knows commenting on the other website blogs give the benefits of backlinks, traffic, and branding of our linked website and we are trying lots of things to create a good backlinks which would give a huge converting traffic to us. Sometime people commenting a those website which doesn’t have good reputation or not a much traffic so, their efforts are not useful for them.

Commenting is the ways to drive traffic that is facebook commenting, twitter commenting or website commenting. Here we are going to tell you about some points which may give you huge traffic to increase comments on your blog.

Blog Comment Points Are:

Get visitors to subscribe: Many readers don’t want to comment at first time on your blog because they don’t have much truest on your blog and they don’t know about how much the traffic on your blog getting. To ask them to subscribe to your blog for more blog or webinar this will help to increase comments, traffic and revenue.

Also Read :   Web Design Jaipur, Web Development Jaipur, SEO Company Jaipur, India

Disable spam prevention methods: If you are using captcha, then you need to remove them so user can comment without any interruption.

Avoid forcing registration: If you are using registration process for commenting on your site ten remove them because this create far too much resistance and makes it much more irritate for your visitors to comment.

Link to your comments section at the end of your post: Lot of blog themes have a problem with its comment section, visitors have to scroll the whole page at the bottom for the commenting. Your blog should have comment link at the top of page with blog title where visitor can click and move directly to comment section.

Go back and think about the audience you’re trying to reach: If you are getting many comments then try to give answer of your visitors which give your attention to your visitor and help you to reach your goal and focus on the right areas.

Also Read :   How to add user profile image by custom URL and custom fields in woocommerce

Leave an unanswered question at the end of your post: Ask a question at the end of blog which is the one of the best ways to get readers attention to comment on your blog. Your aim should to develop a discussion within your comments and the more discussion.

Respond to comments and encourage more conversations: As we talk in Go back and think about the audience you’re trying to reach engaging your audience for getting more comments in general ways to respond to comments for further conversation.

You can let us your point of views in the comment or subscribe us to get more blog from us.

Continue Reading

Trending