简体   繁体   中英

How can we add in code a product to the cart with a custom option type file in Magento?

I am adding the products into Magento's with custom option type file:

$cart = Mage::getModel('checkout/cart');
$cart->init();
$pModel = Mage::getSingleton('catalog/product');
foreach($prodArray as $_prod){
  $products = explode("=",$_prod);
  $product_id = $products[0];
  $prod_qty = $products[1];
  $pModel->unsetData();
  $pModel = Mage::getModel('catalog/product')->load($product_id);
  try {
    $cart->addProduct($pModel,$prod_qty);
  }
  catch (Exception $e) { continue; }
  echo  "<br>Product has been added to Cart of id: $product_id with Quantity: $prod_qty";
}
$cart->save();

I am not EXACTLY sure what you are trying to do based on your title.

I think you want to know how to add a product with options to your cart programmatically?

This link covers that: How to get the URL to a configurable item in Magento? where the visitor mentions a url of the structure: /checkout/cart/add?product=47&qty=1&super_attribute[496]=4

Adding a simple product to your cart programmatically is as simple as following a link of this structure: http://yoursite.com/index.php/checkout/cart/add?product=product_id&qty=qty

Obviously you would need this to be a "real" user that is cookied, etc. Please add more comments if I am not understanding your use case.

Maybe it's too late, but today I faced the same problem and I found a solution. I needed to add a product to the cart, and one of the options was a file.

It works in Magento 1.7 but I haven't tested it on another versions.

// the path of the file, relative to Magento base directory.
// For example /media/image.jpg
$image = "YOURFILE.JPG";
// the ID of the product
$product_id  = XXX;

$product     = Mage::getModel('catalog/product')->load($product_id);

$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty' => 1,
    'options' => array(
        12345 => array(
                'quote_path' => $image,
                'secret_key' => substr(md5(file_get_contents(Mage::getBaseDir() . $image)), 0, 20)),
    )
);

$cart->addProduct($product, $params);
$cart->save();

Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

(12345 is the option ID, you can hardcode it or you can get a list of ID's using this: https://stackoverflow.com/a/8317707 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM