Magento2 Mini Cart – Show Not Visible Individually Products

magento2mini-cart

I have create a ajax call and added a product to cart programmatically. After that i have redirected to direct checkout page. Now mini cart shows similar to attached image. Point to be noted is cart display like below attached image if i add "Not Visible Individually" item in cart.
However it works perfectly if product is set visible on catalog and search from admin.

How can it populate correctly ?

Attached Image:

enter image description here

Add to cart code:

        $productId = $this->getRequest()->getParam('id');
        $params = array(
            'form_key' => $this->formKey->getFormKey(),
            'product' => $productId,
            'qty' => 1        
        );
        $_product = $this->product->load($productId);
        $this->cart->truncate();
        $this->cart->addProduct($_product, $params);
        $this->cart->save();

Best Answer

Override this file

app\code\Namespace\ModuleName\etc\di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\CustomerData\Cart" type="Namespace\ModuleName\CustomerData\Cart" />
</config>

app\code\Namespace\ModuleName\CustomerData\Cart.php

protected function getRecentItems()
{
    $items = [];
    if (!$this->getSummaryCount()) {
        return $items;
    }
 
    foreach (array_reverse($this->getAllQuoteItems()) as $item) {
        /* @var $item \Magento\Quote\Model\Quote\Item */
        if (!$item->getProduct()->isVisibleInSiteVisibility()) {
            $product =  $item->getOptionByCode('product_type') !== null
                ? $item->getOptionByCode('product_type')->getProduct()
                : $item->getProduct();
 
            $products = $this->catalogUrl->getRewriteByProductStore([$product->getId() => $item->getStoreId()]);
            if (!isset($products[$product->getId()])) {
                if ($product->getId() === 10){ // set your condition 
                    $items[] = $this->itemPoolInterface->getItemData($item); // "not visible individually" product having id 10 added into items array
                }
                continue;
            }
            $urlDataObject = new \Magento\Framework\DataObject($products[$product->getId()]);
            $item->getProduct()->setUrlDataObject($urlDataObject);
        }
        $items[] = $this->itemPoolInterface->getItemData($item);
    }
    return $items;
}
Related Topic