产品以编程方式创建

时间:2014-07-22 10:47:24

标签: php magento

我只是想在magento中以编程方式添加简单产品,我尝试了下面的代码

$product = new Mage_Catalog_Model_Product(); 
// Build the product 
$product->setSku(8000); 
$product->setAttributeSetId('some_int_value_of_some_attribute'); 
$product->setTypeId('simple'); $product->setName('order1');  
$product->setCategoryIds(array(4)); # some cat id's, my is 7 
$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend) 
$product->setDescription('Full description here'); 
$product->setShortDescription('Short description here'); 
$product->setPrice(39.99); # Set some price

# Custom created and assigned attributes 
$product->setHeight('500');
$product->setWidth('500');
$product->setDepth('2');
$product->setType('simple');    
//Default Magento attribute 
 $product->setWeight(4.0000); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); $product->setStatus(1); $product->setTaxClassId(0); # My default tax class $product->setStockData(array(
    'is_in_stock' => 1,
    'qty' => 99 )); $product->setCreatedAt(strtotime('now')); try {
    $product->save(); } catch (Exception $ex) {
    //Handle the error }

try{
    $product_model = Mage::getSingleton('catalog/product');

    // Load product
    $_sku = "8000";
    $my_product_id  = $product_model->getIdBySku($_sku);
    $my_product     = $product_model->load(43);
    $qty_value = 1;

    // Add to cart 
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($my_product, array('qty' => $qty_value));
    $cart->save();
    print_r($cart->getItemsQty().PHP_EOL);
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    var_dump("working");  } catch(Exception $e){
    return $e->getMessage(); }

我正在使用magento版本1.9.0.1

但我得到空白页面没有任何错误,产品没有添加到支持。

所以,任何人都可以帮我找到以编程方式创建简单产品的最简单方法。

1 个答案:

答案 0 :(得分:0)

Product save depending on Attribute and store.

首先,检查how many attribute are required for products
第二,You need to set those attribute value to products
第三,

 set store 
 $product->setStore($storeId);

如果您使用脚本执行此代码,请添加below code before start of product create code

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

更多详情: -

http://inchoo.net/ecommerce/magento/programming-magento/programatically-manually-creating-simple-magento-product/

http://www.codetweet.com/magento/create-simple-product-magento-programmatically/