1

I'm working on Magento CE 1.9 and I would like to execute the following code after the customer adds a product to cart:

<?php
$id = '226'; // Replace id with your product id
$qty = '1'; // Replace qty with your qty
$_product = Mage::getModel('catalog/product')->load($id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>

The above code will programmatically add a product to cart. Ultimately, I'm going to test to see if the conditions of a shopping cart price rule are met and if so, run that could which adds a free "gift" or promotional product.

I've got my basic module configured. I'm just curious which event I should make use of that will allow me to add a product and update the cart? These appear to the applicable options:

  • checkout_cart_add_product_complete
  • checkout_cart_product_add_after
  • checkout_cart_update_items_before

So everytime a product from my catalog is added, an event is fired and my code is executed. Thanks in advance.

1

You should go for checkout_cart_add_product_complete (which is run in the addAction of the CartController). checkout_cart_update_items_before isn't appropriate for the action you're describing, and checkout_cart_product_add_after is triggered on addProduct, which will cause an issue because you are using this exact function in your observer.

0

try to use controller_action_postdispatch_cart_index_add and check wheather your condition matches and add your code to add product to cart

  • 1
    I wouldn't recommend that. Some modules (ajax Add to Cart f.e) use customer controllers. Which means this one wouldn't be executed any more. – Mayers Feb 1 '16 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.