Unlock Big Savings: Magento 2 Cart Price Rule Custom Options

How to Add Magento 2 Cart Price Rule Custom Options

Adding Magento 2 cart price rule custom options to the “Action Apply” field is a straightforward process. You’ll need to extend the cart price rule form in the admin panel to include your custom options. By doing this, you can modify how discounts are applied, providing tailored promotional offers to your customers.

The dropdown options are rendered by the getMetadataValues() function, which is available in Magento\SalesRule\Model\Rule\Metadata\ValueProvider.php

So, you can create a plugin for this because it’s a public method. I created a plugin for it and got the desired output.

  1. Create di.xml to set the plugin at app/code/Fixnblog/CustomPlugin/etc/adminhtml :
<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\SalesRule\Model\Rule\Metadata\ValueProvider">
      <plugin name="salesrule-plugin" type="Fixnblog\CustomPlugin\Plugin\Rule\Metadata\ValueProvider" sortOrder="1" />
    </type>
</config>

2. Now, create the plugin file ValueProvider.php to add a custom option for the dropdown at Fixnblog\CustomPlugin\Plugin\Rule\Metadata:

<?php

namespace Fixnblog\CustomPlugin\Plugin\Rule\Metadata;

class ValueProvider {
    public function afterGetMetadataValues(
        \Magento\SalesRule\Model\Rule\Metadata\ValueProvider $subject,
        $result
    ) {
        $applyOptions = [
            'label' => __('Popular'),
            'value' => [
                [
                    'label' => 'The Cheapest, also for Buy 1 get 1 free',
                    'value' => 'buy-1-get-1-free',
                ],
                [
                    'label' => 'Get $Y for each $X spent',
                    'value' => 'get-y-for-each-x-spent',
                ],
            ],
        ];
        array_push($result['actions']['children']['simple_action']['arguments']['data']['config']['options'], $applyOptions);
        return $result;
    }
}

Output:

Cart Price Rule Custom Options
Magento 2 cart price rule custom options in the admin panel

To create a cart price rule in Magento 2, please refer to the following link for a comprehensive guide.

Magento 2 Upgrade Old Script to Declarative Schema

Leave a Reply

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