Monday, December 19, 2011

Magento : Add or create new product magento through code with custom options

<?php 
//  Add or create  new product magento through code with custom options, image and manage stock
// mmoves image and assigns to all three types image, small_image and thumbnail_image
require_once 'app/Mage.php';
umask(0);
$app = Mage::app();
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));



//create a new product
try {          
    
  $serverurl = $_SERVER['DOCUMENT_ROOT'].'/Client/demos/tfasigns/img_output_.jpg';
  $product = Mage::getModel('catalog/product');
  $stockData = $product->getStockData();
        $stockData['qty'] = 10;
        $stockData['is_in_stock'] = 1;
        $stockData['manage_stock'] = 1;
        $stockData['use_config_manage_stock'] = 0;
   $options = array();
        $options = array(
            'title' => 'Option Title',
            'type' => 'radio',
            'is_require' => 1,
            'sort_order' => 0,
            'values' => array()
        );
        $options['values'][] = array(
            'title' => 'Option Value 1',
            'price' => 0.00,
            'price_type' => 'fixed',
            'sku' => '',
            'sort_order' => '1'
        );
        $options['values'][] = array(
            'title' => 'Option Value 2',
            'price' => 89.00,
            'price_type' => 'fixed',
            'sku' => '',
            'sort_order' => '1'
        );
 
    $product->setStoreId('default')
    ->setTypeId('simple')  
    ->setAttributeSetId(4)
    ->setName('4You banner5')
    ->setDescription("This widget will give you years of trouble-free widgeting.")
    ->setShortDescription("High-end widget.")
    ->setSku('4you5')
    ->setWeight(1.0)
    ->setStatus(1)
    ->setVisibility(4)
    ->setPrice(15.49)
    ->addImageToMediaGallery($serverurl,array('thumbnail','small_image','image'),true,false)
    ->setTaxClassId(0)
    ->setStockData($stockData)
    ->setCategoryIds('3')
    ->setHasOptions(1)
    ->setProductOptions(array($options))
    ->setCanSaveCustomOptions(true)
    ->save();  
 
  echo 'OK Product ID: '.$product->getId();
 
      $cache = Mage::getSingleton('core/cache');
      $cache->flush();
}
catch (Mage_Core_Exception $e) {
  echo $e->getMessage();
}
catch (Exception $e) {
  echo $e;
}


?>

1 comment: