Changing the limit of cross-sell products in the cart – Magento 2

In Magento 2, by default, a maximum of four products are displayed in the cross-selling section of the cart. In many stores, this limitation is burdensome – especially when the offer is extensive.

Default cross-sell limit in Magento 2

In a standard Magento 2 installation, the limit of cross-selling products in the cart is 4. This value is permanently defined in the Magento_Checkout module and cannot be changed from the administration panel.

Where the cross-sell limit is defined

The limit is defined in the Magento_Checkout module – in the Crosssell class. File path: vendor/magento/module-checkout/Block/Cart/Crosssell.php.

As we mentioned above, Magento does not provide configuration for this, so the only correct solution is to overwrite the class using your own module.

Changing the cross-sell limit via your own module

You need to create files:

– preference registration file (di.xml)

– file overwriting the limit

LionBrothers/CrosssellLimit/etc/frontend/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Block\Cart\Crosssell" type="LionBrothers\CrosssellLimit\Block\Cart\Crosssell"/>
</config>

LionBrothers/CrosssellLimit/Block/Cart/Crosssell.php

<?php

namespace LionBrothers\CrosssellLimit\Block\Cart;

class Crosssell extends \Magento\Checkout\Block\Cart\Crosssell
{
    /**
     * Items quantity will be capped to this value
     *
     * @var int
     */
    protected $_maxItemCount = 8;
}

You also need to remember the standard files of each module – registration.php and module.xml.

Why preference? Why not plugin?

In this case, the cross-sell product limit is set as a protected property, not a method. This means we can’t change it via plugin (before/after/around). The simplest solution (and best practice) is to use preference and extend the original class.

Comments

Leave a Reply

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