Magento 2 : Split basket items based on condition or product attributes

Today we are going to cover how to split basket or cart items in Magento 2 based on condition or product attribute. We had a requirement for one our of clients where they wanted to do personalization on certain products which can be bought with or without personalization. In this case, we were not using out of the box Magento 2 custom options for better management of these personalizations. Hence the challenge was to

Anyways let’s crack on with code to see working examples based on specific condition to split basket or cart items.

Step 1 – Add the following entry in \etc\di.XML of your module

<type name="Magento\Quote\Model\Quote\Item">
    <plugin name="scommerce_custom_quote_item_split" 
            type="Scommerce\Custom\Plugin\Quote\SplitItemPlugin" />
</type>

Step 2 – Create a plugin class – \Scommerce\Custom\Plugin\Quote\SplitItemPlugin.php with the following code


<?php

declare(strict_types=1);

namespace Scommerce\Custom\Plugin\Quote;

use Closure;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use Magento\Framework\App\RequestInterface;

class SplitItemPlugin
{
    public function aroundRepresentProduct(QuoteItem $item, Closure $proceed, $product): ?bool
    { 
        if ($product->getCustomPersonalisation()) {
              return false;
        }
        
        return $proceed($product);
    }
}

As you can see we have added a condition which is a product attribute (custom_personalisation). And checking if the added product has custom_personalisation set to YES or NO in the admin. If yes then split the basket otherwise don’t.

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *