Yes, I know. This topic has already been discussed here. But it seems the article isn’t really helpful for those people who would integrate Magento into a custom website because it will redirect the page to Magento’s default web store provided in the installation. The technique I’ll discuss here assumes that you know HTML and ofcourse familiar with Object Oriented Programming (OOP) in PHP.
Let’s start.
We begin our index.php page with a HTML form having one (1) textbox for quantity and a submit button.
<form action="process.php"> Product name: T-shirt <br> Quantity: <input type="text" name="qty[<?=$productID?>]"> <input type="submit" value="Add to Cart"> </form>
where $productID is the ID of the product that you want to add into your shopping cart and process.php is the file that will do the processing of the form. Also upon submission of the form, the qty field will pass the value into an array format similar to one below:
"qty" = array(12345 => 1)
where
qty is the field name
12345 is the product ID and
1 is the qty value
This will be the content of process.php file:
Include the Mage.php file on top of the process.php. Click here to see how.
Then proceed with the php script below:
// continuation of process.php $items = $_POST["qty"]; // get the current Magento cart $cart = Mage::getSingleton('checkout/cart'); foreach($items as $key => $value) { // 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($key); // start adding the product $cart->addProduct($product, array('qty' => $value)); // 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");
That’s it! I didn’t add the end tag for php since it isn’t required for pure php file. I included alot of comments within the code to explain how each line works. If it causes you some problems, just remove the comments 🙂
Do you have any idea to open product detail page using product id?
Yes. It is done using the code below:
using $product you can now access the details of the specified id. For example, you can view all the details by running the code below:
And how would you remove the product 🙂
I tied:
$cart = Mage::getSingleton(‘checkout/cart’);
$cart->removeItem($item_id); //item_id not product_id
$cart->save();
Mage::getSingleton(‘checkout/session’)->setCartWasUpdated(true);
but it did not work 🙁
btw thanks for your article it already helped me a LOT!
cheers!
It’s quite easy 🙂
Set the quantity to 0
Thanks :p
Hi !
How to add bundle with option ?
Thanks
Any idea how to add a configurable product via URL?
I tried adding the configurable option IDs as in your methos but they seem to not catch.
Thanks
I have the cookie location set for ‘/’ and it doesn’t work. I’m using latest version of Magento. I’ve tried countless variations of this script gleaned from the internet and it does not work. What location is the script running from? Does that matter? Did this functionality disappear in a recent upgrade?
I can not get into a Magento session from a script in a different folder on the same server for the life of me. Very frustrating.
I’m trying to bridge Magento and SMF and I have the Magento side down and done, but connecting TO Magento from SMF is just not working…
Anyone know how to accomplish this besides API?
thanks
alex, are you making sure you have this being called on your page?
Hi, great post.
I’m currently going through so that when a certain product is added to the cart and they are from such and such location then it adds a associated fee.
I’ve got it set up so when they checkout it’s adding the fee as a product kind of like what you’ve done above.
115,
'qty' => $qty,
);
$product = new Mage_Catalog_Model_Product();
$product->load(115);
$cart->addProduct($product, $params);
$cart->save();
?>
This works awesome, but my trouble is if they refresh the page or go away and come back to the page it adds the product again. Do you knowhow I could do some sort of product checking so if it’s been added it can’t be added again, or how to set the qty after the cart->save function?
Let me know, thanks.
Thanks Ben!
I think it will behave that way unless you’ll do a couple of checking to your cart value. Refreshing the page will always add the product in the cart as long as your valid get/post values are still present which makes the $cart->addProduct() function to return TRUE. There are several ways you can prevent same data from being used more than once but I think these are the most common:
1. Creating a separate confirmation page for successful/failed add to cart request, or;
2. Do the validation on the same page.
If you choose the last option, you can check if the productid is already present in the cart. If it is, then you can get the current qty and add your new qty value to it. Removing a product in the cart also works this way because setting the qty to zero deletes the item from the cart.
You can experiment using the functions getProductIds and updateItems found in the Magento Documentation
Removing an item with qty to 0 does not work. instead use this:
$items = $cart->getItems();
foreach ($items as $item) {
if ($product->getId() == $product_id) {
$itemId = $item->getItemId();
$cart->removeItem($itemId);
Mage::getSingleton(‘checkout/session’)->setCartWasUpdated(true);
break;
}
}
Sorry, more information for above:
The product id for adding a product is not the same as the id for removing.
– Iterate through the cart items
– Get the product id and compare with the product id you want to remove.
– Remove the product
– Break out of the loop when product is found and deleted.
Missing a $cart->save(); in the above code.
Best regards,
John.
Hi!
Great post, it help me a lot!
However, I have a question! How do I add a product with customs options?
For exemple a t-shirt with different color and size?
Thanks in advance for your answer
Gauthier
Hello Gauthier,
Thanks for reading my blog. Regarding your question, please check my follow up post regarding the matter here
Keep on reading!
Richard
[…] 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 […]
Hi!!!!
thanks for this script…. 🙂
but I want to save a product as new product by submitting a form in a script
what will be the code???????
please help me
again thanx in advance
In made auction module,when auction over i want to add product of winner user only in that how set customer id of winner user add to cart……..
You can use
setCustomer()
to indicate which user you want to use for that session.Hi, Great post. I have dug around everywhere on a way to do this… Do you know how I can do what you have above and have it alter the line total, sku, title etc etc?
I have managed to do this by placing an order without any trouble but I need it to sit in the basket so that the customer can place the order.
Many thanks!
Great tut thanks Richard. How would I add a custom option which is a checkbox?
I would like to link the products in my Magento to my main website popnovels do you know how I could write in the redirect from the product image to the product on my main site. http://www.popnovels.com. Currently I have a dummy site set up at http://www.popgnovels.com with one book in it and am trying to get it to link to the product. I have the address to the products on popnovels I just am lost on how to get the code to respond the way I want.
I want to add products from prestashop to magento shopping cart is this possible ?
Yeah. Just follow the post.
Hi!
Great post, it help me a lot!
Hi,
If a customer want a product in large qty like:30qty.
We a have a product and the qty is 5. and we have same product(duplicate product) and qty is 50.
then i want to save products in shopping cart like : take first product qty i.e 5 and another product take 25 qty.
But when we select 30 qty and click on add to cart button then we can not go to shopping cart page.
Please solve the problem.
Thanks
Vishal
Is there an error page after clicking the add to cart button? Those two products are treated as two different items regardless if they are duplicate since they would have different IDs in the database.
Hi,
I am using magento 1.7.2 and I want to add some external products in magento cart and I am trying your code but not working. can u help me on this point?
Thanks in advance.
Manoj Kumar
How did you implement it?
Hi Richard,
Thank you for the great post!
I understand that this post was made few years ago, so there might be some slight changes to the code now. I’m currently using the latest stable version of Magento (ver 1.7.0.2) and the code above is not anymore working. If it’s not too much too ask, it would be greatly appreciated if you can post some updates for the latest Magento version. 🙂
Best Regards,
Gift
Sorry for the late reply. I’ll try to update it over the weekend. Thanks 🙂
Hi Richard,
Thank you for the update. I somehow managed to implement the add to cart button, but I understand the product is already set and predefined in Magento site right?
Here’s my case and what I’d like to achieve:
I currently have a Custom Product Builder (Gun Customization) where users can select customize parts of their choice and eventually add this to their cart. The custom builder is a separate file from Magento. Since it’s a customized product, it would be difficult to add them one by one thru Magento. So what I’d like to do everytime a user submits the customize product is to add this automatically to Magento. I mean not setting/creating the product thru Magento admin but creating the product externally. Is this possible?
Your positive response will be greatly appreciated.
Thank you.
Regards,
Gift
Hello sir I have to display direct my cart page open when user click on add to cart button pls help me
I am using magento 1.7 on my local server for now, and when i insert this code nothing happens, can you please help me.
Thanks
Post your code here
Hi Richard,
I’d have following problem: the magento site and external site are hosted on two different domains.
OK, so I can get access to magento site over SOAP-API. I want the user to be redirected from this external site to magento shopping cart page, as soon as the user presses “My cart” button.
With the help of SOAP-API I’ll get sessionID, and cartID.
Is it possible to open that specific shopping cart, by passing these two parameters over POST or GET method to magento server?
Thanks in advance.
I haven’t tried that yet. You can, however, pass the session ID across two system but this is pretty much open to attack.
you need to $cart->init() – before $cart->addProduct() – in order to be able to add multiple items to the cart
I am using Amazon CheckOut Button in my Magento Store but problem is that when i click the button it doesn’t contain cart products.
My code : (I place it in cart.phtml)
//
//
The Simple, Truseted way to Pay.
Thanks for the coding you provided for add product in shopping cart. It’s a helpful info for me.
Hi sir, have a question, hope you would help me on this thing. How do i get the input field qty value in addtocart. not in cart result sir.
Thanks so much.. I got what i wanted
Thanks too
you need to $cart->init() – before $cart->addProduct() – in order to be able to add multiple items to the cart