Magento Themes and Magento Extensions

How to add a product with custom options into Magento shopping cart from an external site?

Share

This is a follow up post to a previous article I wrote on how to add products into Magento but this time the script includes custom options (attributes) of the product. I used Magento version 1.4.0.1 in this example. Just copy the whole script and save it as index.php.

01 <?php
02 require_once ("/var/www/your-magento-directory/app/Mage.php");
03 umask(0);
04
05 // Initialize Magento
06 Mage::app("default");
07
08 // You have two options here,
09 // "frontend" for frontend session or "adminhtml" for admin session
10 Mage::getSingleton("core/session", array("name" => "frontend"));
11
12 // get the current Magento cart
13 $cart = Mage::getSingleton('checkout/cart');
14
15 if(isset($_POST['submit'])){
16
17 // call the Magento catalog/product model
18 $product = Mage::getModel('catalog/product')
19 // set the current store ID
20 ->setStoreId(Mage::app()->getStore()->getId())
21 // load the product object
22 ->load($_POST['product']);
23
24 // start adding the product
25 // format: addProduct(<product id>, array(
26 //         'qty' => <quantity>,
27 //         'super_attribute' => array(<attribute id> => <option id>)
28 //     )
29 // )
30 $cart->addProduct($product, array(
31 'qty' => $_POST['qty'],
32 'super_attribute' => array( key($_POST['super_attribute']) => $_POST['super_attribute'][525] )
33 )
34 );
35
36 // save the cart
37 $cart->save();
38
39 // very straightforward, set the cart as updated
40 Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
41
42 // redirect to index.php
43 header("Location: index.php");
44
45 }else{
46 ?>
47 <html>
48 <head></head>
49 <body>
50 <div style="width: 400px; margin: auto">
51 <h3>Very Nice T-shirt</h3>
52 <hr>
53 <div style="width: 180px; margin:auto; line-height: 30px">
54 <form action="index.php" method="post">
55 Size:
56 <select name="super_attribute[525]">
57 <option value="">Choose an option...</option>
58 <option value="100">Small</option>
59 <option value="99">Medium</option>
60 <option value="98">Large</option>
61 </select><br>
62 Quantity: <input type="text" name="qty" size="1"value="1">
63 <input type="submit" name="submit" value="Add This">
64 <input type="hidden" name="product" value="119">
65 </form>
66 </div>
67 <hr>
68 <strong><?php echo "Cart Qty: ".$cart->getItemsQty();?></strong>
69 </div>
70 </body>
71 </html>
72 <?php } ?>

Comments are closed.