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

In: Feeling guru

4 Jun 2010

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.

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

Avatar

Bill UNITED STATES

July 18th, 2010 at 9:10 pm

So how can we perform this within WordPress if the mage-enabler is plugged in.

Avatar

Richard Feraro

July 18th, 2010 at 10:32 pm

You have to do the programming based on your need.

Avatar

Scott Greenwald UNITED STATES

July 19th, 2010 at 3:07 pm

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?

Avatar

Richard Feraro

July 19th, 2010 at 5:01 pm

Yeah it should allow you to do that. What are the fields that you plan to add from an external page?

Avatar

Scott Greenwald UNITED STATES

July 21st, 2010 at 12:09 am

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.

Avatar

Richard Feraro UNITED STATES

July 21st, 2010 at 3:48 pm

Yeah it is possible. Read it here.

Avatar

Scott Greenwald UNITED STATES

July 22nd, 2010 at 1:58 am

Yeah, that’s all greek to me. Can I hire you to do it? Please send me an email if you’re interested

Avatar

Eldonthian McAllister UNITED STATES

September 28th, 2010 at 6:28 am

Hey, how would we add Multiple products at the same time.. ? one simple and one with options?!

Avatar

Richard Feraro UNITED STATES

September 29th, 2010 at 12:17 am

Hi,

You can put them in an array then do a foreach loop calling the $cart->addProduct() in each record.

Avatar

Eldonthian McAllister UNITED STATES

September 28th, 2010 at 7:25 am

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[]?

Avatar

Ben AUSTRALIA

October 29th, 2010 at 9:42 am

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

Avatar

Richard Feraro UNITED STATES

October 29th, 2010 at 5:08 pm

To display a product attribute, use the code below:

$product = Mage::getModel('catalog/product');
$product->load(product-ID-here);
echo $product->getData('attribute_code');

Avatar

tuba

November 8th, 2010 at 2:00 am

oh… very nice!

Thank you very much, I have been searching this module for last 2-3 days. Thanks Richard!

Avatar

Richard Feraro PHILIPPINES

November 8th, 2010 at 12:12 pm

You’re welcome 🙂

Avatar

Ben AUSTRALIA

November 8th, 2010 at 11:25 pm

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

Avatar

Richard Feraro UNITED STATES

November 9th, 2010 at 1:01 am

Hi Ben, try the code below:

$item->getData('attribute_code');

Avatar

Ben AUSTRALIA

November 9th, 2010 at 5:39 am

Hi Richard,

Didn’t work… value is empty

Avatar

Richard Feraro PHILIPPINES

November 9th, 2010 at 12:08 pm

Hmmm, it should display something because $item must be a product object. How about doing this:

print_r($item);

It should display the product object in it.

Avatar

Ben AUSTRALIA

November 9th, 2010 at 2:38 pm

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

Avatar

Richard Feraro UNITED STATES

November 9th, 2010 at 5:18 pm

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'));
}

Avatar

Ben AUSTRALIA

November 9th, 2010 at 7:54 pm

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’ )

);
…….

Avatar

Richard Feraro UNITED STATES

November 9th, 2010 at 9:15 pm

If you extended it, then it is just treated as an array which is accessible via getData(). I tested the script and it is working.

Avatar

Ben AUSTRALIA

November 10th, 2010 at 7:44 am

Are you able to post your code and advise on any config.xml adjustment so i can test it from my end.

Cheers

Avatar

Richard Feraro UNITED STATES

November 10th, 2010 at 10:45 pm

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.

Avatar

maged INDIA

December 15th, 2010 at 6:32 pm

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

Avatar

Dave UNITED STATES

January 10th, 2011 at 1:38 am

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…

Avatar

Richard Feraro PHILIPPINES

January 10th, 2011 at 1:51 am

The only instructions needed by the plugin is found in the Installation tab. After that, check the Description page “Is this plugin for you?” section.

Avatar

impi

October 15th, 2011 at 1:00 am

Dude…you’re a legend
Thank you,

Avatar

Richard Feraro PHILIPPINES

October 15th, 2011 at 1:11 am

Thanks 🙂

Avatar

richard PHILIPPINES

October 18th, 2011 at 8:43 pm

galing mo pare ^_^

Avatar

Richard Feraro

October 18th, 2011 at 10:37 pm

Thank you ^_^

Avatar

Nicola ITALY

October 26th, 2011 at 7:27 pm

Hi!
Really good article!

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

Thanks a lot!!!

Avatar

Richard Feraro

October 26th, 2011 at 8:25 pm

Thanks 🙂

Yes, you just need to figure out the right array format.

Avatar

Nicola ITALY

November 27th, 2011 at 6:50 pm

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

Avatar

Nicola ITALY

December 11th, 2011 at 7:03 pm

Resolved! Thanks a lot!!

Just one question… How can I add a message with the order?

Thanks a lot!!!

Nicola

Avatar

Richard Feraro PHILIPPINES

December 12th, 2011 at 12:35 pm

Is it for the confirmation email of the order?

Avatar

Silu UNITED KINGDOM

January 18th, 2012 at 6:48 pm

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

Avatar

Richard Feraro

January 19th, 2012 at 12:11 pm

Thank you Silu 🙂

Avatar

Agemuf PORTUGAL

March 8th, 2012 at 3:40 am

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?

Avatar

gorave

March 20th, 2012 at 6:17 pm

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..?

Avatar

melissa UNITED STATES

May 3rd, 2012 at 11:13 pm

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.

Avatar

Sandip Kasar

August 4th, 2012 at 3:51 pm

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.

Avatar

Michael UNITED STATES

March 13th, 2013 at 3:26 pm

We have a wordpress / Magento project for you. Email me please.

Avatar

Noel

April 7th, 2013 at 2:33 am

Hi!, just a quick question, I’m following a custom option tutorial
on this site:
http://subesh.com.np/2009/12/adding-custom-options-product-magento/

and this : http://pravams.com/2011/05/25/magento-create-custom-options-dynamically/

and will probably use your code for my future projects, now, where exactly do I put the codes given on those links. can you pls help me sir? 🙂

Avatar

Umesh

June 21st, 2013 at 8:04 pm

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

Comment Form

About my blog

This blog is targeted towards all levels of developers and also designers. Various topics are discussed such as Magento, PHP & MySQL, jQuery, WordPress, CSS and HTML.

Booking.com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 5,243 other subscribers

WordPress + Magento

Recent Trackbacks

Archives

Disclaimer

All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or my mom.