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 etcdi.XML of your module

<type name="MagentoQuoteModelQuoteItem"> <plugin name="scommerce_custom_quote_item_split" type="ScommerceCustomPluginQuoteSplitItemPlugin" />

Step 2 – Create a plugin class – ScommerceCustomPluginQuoteSplitItemPlugin.php with the following code

 <?php declare(strict_types=1); namespace ScommerceCustomPluginQuote; use Closure;
use MagentoQuoteModelQuoteItem as QuoteItem;
use MagentoFrameworkAppRequestInterface; 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.