Sunday, September 25

Tips to Creating Magento Products On-The-Fly

Sometimes it’s necessary to create products on-the-fly, typically in situations where there are so many product possibilities that even a configurable product isn’t flexible enough! In such situations the need arises to create products dynamically.

Below is the PHP code to produce a single Magento product and add it to the cart.

<?php
require_once ‘app/Mage.php’;
Mage::app();
[/php] [php]
// instatiate Product
$product = Mage::getModel(‘catalog/product’);

$product->setWebsiteIds(array(1));
$product->setSku(‘rand-sku-’ . rand());
$product->setPrice(rand(100,2000));
$product->setAttributeSetId(4);
$product->setCategoryIds(array(3));
$product->setType(‘Simple Product’);
$product->setName(‘Product Name’.rand(1,200000));
$product->setDescription(‘The Product Description’);
$product->setShortDescription(‘Brief Description’);
$product->setStatus(1);
$product->setTaxClassId(‘2′);
$product->setWeight(0);
$product->setCreatedAt(strtotime(‘now’));

/* ADDITIONAL OPTIONS

$product->setCost();
$product->setInDepth();
$product->setKeywords();

*/

$product->save();

// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!

$stockItem = Mage::getModel(’cataloginventory/stock_item’);
$stockItem->assignProduct($product);
$stockItem->setData(’is_in_stock’, 1);
$stockItem->setData(’stock_id’, 1);
$stockItem->setData(’store_id’, 1);
$stockItem->setData(’manage_stock’, 0);
$stockItem->setData(’use_config_manage_stock’, 0);
$stockItem->setData(’min_sale_qty’, 0);
$stockItem->setData(’use_config_min_sale_qty’, 0);
$stockItem->setData(’max_sale_qty’, 1000);
$stockItem->setData(’use_config_max_sale_qty’, 0);

$stockItem->save(); 
?>

hope it helps... thanks...

No comments:

Post a Comment