Magento – How to check if a product is already in the cart

cartmagento-1.9productproduct-collectionup-sells

I have this block of code which displays product from a certain category in the cart for last minute buys.

<?php
$categoryid = 1103;
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));?>

<div class="upsell_products">
<?php $i = 0; ?>
<?php foreach ($collection as $_product){ ?>
<?php $product = Mage::getModel('catalog/product')->load($_product->getId());?>
<div class="product">
<a href="<?php echo $_product->getProductUrl() ?>">
<div class="product_img_cart">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image'); ?>" alt="<?php echo $_product->getName(); ?>" /></a>
</div>
<a href="<?php echo $_product->getProductUrl(); ?>">
<p class="upsell_pro_name"><?php echo $_product->getName(); ?></p>
<p class="upsell_pro_price">
<?php echo Mage::helper('core')->formatPrice($_product->getPrice());?></a></p>
<div class="add_cart_btn">
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($product)?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
</div>
</div>
<?php if($i++ == 4) break; ?>
<?php }?>
</div>

I want to add in a check so that if one of the "upsell" products are already in the cart then it is not offered to the customer.

If this doesn't make sense or you need me to explain more please just ask

Thank you

Best Answer

See app\code\core\Mage\Checkout\Block\Cart\Crosssell.php:

protected function _getCartProductIds()
{
    $ids = $this->getData('_cart_product_ids');
    if (is_null($ids)) {
        $ids = array();
        foreach ($this->getQuote()->getAllItems() as $item) {
            if ($product = $item->getProduct()) {
                $ids[] = $product->getId();
            }
        }
        $this->setData('_cart_product_ids', $ids);
    }
    return $ids;
}

So for your collection you can add

$collection->addFieldToFilter('entity_id', array('nin'=>$idsInCart));
Related Topic