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.

<?php
require_once ("/var/www/your-magento-directory/app/Mage.php");
umask(0);

// Initialize Magento
Mage::app("default");

// You have two options here,
// "frontend" for frontend session or "adminhtml" for admin session
Mage::getSingleton("core/session", array("name" => "frontend"));

// get the current Magento cart
$cart = Mage::getSingleton('checkout/cart');

if(isset($_POST['submit'])){

	// call the Magento catalog/product model
	$product = Mage::getModel('catalog/product')
					 // set the current store ID
					 ->setStoreId(Mage::app()->getStore()->getId())
					 // load the product object
					 ->load($_POST['product']);
	
	// start adding the product
	// format: addProduct(<product id>, array(
	//         'qty' => <quantity>, 
	//         'super_attribute' => array(<attribute id> => <option id>) 
	//     ) 
	// )
	$cart->addProduct($product, array( 
			'qty' => $_POST['qty'], 
			'super_attribute' => array( key($_POST['super_attribute']) => $_POST['super_attribute'][525] )
			)
		);
		
	// save the cart
	$cart->save();
	
	// very straightforward, set the cart as updated
	Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
	
	// redirect to index.php
	header("Location: index.php");

}else{
?>
<html>
<head></head>
<body>
<div style="width: 400px; margin: auto">
	<h3>Very Nice T-shirt</h3>
	<hr>
	<div style="width: 180px; margin:auto; line-height: 30px">
		<form action="index.php" method="post">	
			Size: 
			<select name="super_attribute[525]">
				<option value="">Choose an option...</option>
				<option value="100">Small</option>
				<option value="99">Medium</option>
				<option value="98">Large</option>
			</select><br>
			Quantity: <input type="text" name="qty" size="1" value="1"> 
			<input type="submit" name="submit" value="Add This">
			<input type="hidden" name="product" value="119">
		</form>
	</div>
	<hr>
	<strong><?php echo "Cart Qty: ".$cart->getItemsQty();?></strong>
</div>
</body>
</html>
<?php } ?>

About the author

Richard Feraro is a Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

By Richard Feraro

Richard Feraro is a Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

45 thoughts on “How to add a product with custom options into Magento shopping cart from an external site?”
  1. Very nice! I think this covers what Ive been looking for. Can we also pass form entries to the Magento cart?
    I would like to have a mini-form in wp that on submit auto populates the corresponding fields in onepage checkout, allowing users to complete the order. Is this possible?

      1. I have an external page where I’m selling one bottle of a weight loss product.
        The form consists of:
        First Name
        Last Name
        Address
        City
        State
        Zip
        Country
        Email
        Phone

        Submit would auto populate those fields in magento checkout, allowing users to complete the form and submit payment.

  2. In my case, I have a down loadable product, While I only have one link, it is basically a simple product with options, I thought. does this link exist as a super_attribute? where do I find it?or is it something else.. such as links[]?

  3. Hi
    I have a product that have attributes. How do i access the attribute value so I can display it in the shopping cart

  4. Hi Richard,
    I have a situation where I need to access the shopping cart item attributes
    I have a products that has 3 attributes each attribute has a price. The user needs to select one attribute to add the product to cart. How do i get the attribute value of the added product… Below is my snapshot of my code
    $this->_quote = parent::getQuote();
    $quote = $this->_quote;
    $quote_items = $quote->getAllItems();
    foreach($quote_items as $item){
    // I want to get the attribute value using the $item object
    }
    Thanks

    Ben

        1. Here is a snapshot from print_r($item);
          I want to get the value of myprice and price_type
          =================================================
          [_origData:protected] => Array ( [option_id] => 144
          [item_id] => 138
          [product_id] => 167
          => info_buyRequest [value] => a:3:{s:3:”qty”;s:1:”1″;s:4:”qty2″;s:1:”1″;s:15:”super_attribute”;a:2:{s:29:”myprice”;s:7:”30.0000″;s:17:”price_type”;s:3:”type1″;}}
          )
          =================================================

          Thanks

          Ben

        2. Try this:

          $quote = Mage::getSingleton('checkout/session')->getQuote();
          foreach($quote->getAllItems() as $item){
          	$product = Mage::getModel('catalog/product')->load($item->getProduct()->getId());
          	print_r($product->getData('myprice'));
          	// or
          	print_r($product->getAttributeText('myprice'));
          }
  5. Hi Richard
    It did not work I think because ‘myprice’ and ‘price_type’ are not product attributes…
    I have extended Mage_Checkout_CartController and rewrite Addaction function below is snapshot.
    public function addAction()
    {
    $cart = $this->_getCart();
    if ($_POST[‘price_type] == ‘1’) {
    $params = array(
    ‘qty’ => $_POST[‘qty’],
    ‘super_attribute’ => array(‘my_price’=> $_POST[‘price’],
    ‘price_type’=>’type1’ )

    );
    …….

    1. My config.xml is the same as it was when I downloaded it and installed. Maybe your customization in the checkout cart controller prevents you from using the proper method in Magento in accessing the attributes. I would advise that you follow the right way of adding attributes for a product in the administration panel so you can use the codes I provided earlier.

  6. Hi,

    Can you please help me that how can i set custom price for the product added in cart .
    I have override the cart controller add action to add product.

    i want to use custom price to be set for the product in cart.

    Thanks

  7. Is there a users manual for this… I just want to embed the content area of my magento site into a page on wordpress so people can view products are checkout without leaving my blog…

  8. Hi!
    Really good article!

    Can I also insert the price into Magento shopping cart from external web-site?

    Thanks a lot!!!

  9. Hi, I’m running Magento 1.5, there’s no way to add product with this script O_O

    I copy the whole script in a subdirectory under magento install, then I run the script but I can’t understand why no product appear in my magento cart

    Any Ideas?

    Thanks a lot 😉

    Nicola

  10. Richard, thank you for this. I’m also impressed with the patience you show to some of the ungrateful commenters on your blog!

  11. Do you know how to had custom options of a product in order email that is sent to the customer and to the store owner?

  12. Hello mam, i need to convert a lead to an opportunity. i need to get customer details from magento and pass it on to sugarcrm to convert the existing lead to an opportunity. whenever a customer click on Add to Cart button to add a product to the shopping cart. we need to get cart information , product information and customer information and pass it on the details to the SugarCRM. Can u suggest me any links..?

  13. Is there a way to have a querystring or something to pass the information from an external site to the product page in the magento store before adding it to the cart?

    Any help would be greatly appreciated, thanks.

  14. I used Mhitech Magento free theme. In that theme i want vertical category navigation box in left side any one guide me how i can do this.

  15. Hi,

    I have an issue when i use custom option like weight in a product (simple product) and i want to add to cart that product then it give me an error “Please specify the product required option(s)”.

    Please give a solution

    Thanks
    Umesh

Leave a Reply