Cart – Hide ‘Add to Cart’ Button if Specific Products Already in Cart

cartdevelopmentproduct

I have 100 products in my store. 4 products (all in one category) are "special products" that cannot be purchased in the same cart with other 96 products. I would like to hide the "Add to Cart" button on the other 96 products if any of the 4 "special products" have been added to the cart.

The 4 "special products" CAN be purchased together, so I do not want to hide the "Add to Cart" button on those products. Only want the button hid on the other 96 products that are not compatible with the 4 "special products".

My template uses $_product->isSaleable, so I thought there would be a way to hide the button on the 96 products using that somehow. Being relatively new to Magento, I have not been able to figure out how to accomplish this. Might be the completely wrong way as well.

The 4 "special products" use a custom design, so my thought process was to simply remove $_product->isSaleable from that design template (the products are never out of stock and will always be available.)

A secondary option would be to block customers from adding one of the 96 products to the cart, and simply display a notice/message that informs them that they can't add to the cart because of the special product(s) already in the cart.

I am using Magento CE 1.8.1.

Best Answer

If you are unable to save the products into a "special" category as @Julien suggested, you could set a different attribute set specifically for the products, or, if you can do neither of those, I would suggest setting a product attribute. Any way you do it, you'll still have to query the DB for these products, then grab your Cart and see if any items are in it.

So, let's create a product attribute, and call it "featured". Make a new attribute, as a Yes/No and assign it to the appropriate attribute set. Flag those 4 products as such.

Next, you need something along the lines of:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute'=>'featured','eq'=>'1'));

$exemptProducts = array();
$exemptProductFound = false;

foreach ($collection as $product) {
    $exemptProducts[] = $product->getId();
}

// now let's check if any are in the basket
$cart = new Mage_Checkout_Model_Cart();
$cart->init();

foreach ($cart->getItems() as $item) {
    if(in_array($item->getProductId(), $exemptProducts)) {
        // to make it simple, just set a flag
        $exemptProductFound = true;
    }
}

This could be in-line in your template, or in a function that you make available to your template (cleaner).

Related Topic