Magento – Magento 2 : I need to change add to cart success message after adding product into cart through plugin

addtocartmagento2success-message

I need to change add to cart success message after adding product into cart through plugin.

Currently i have used below code for override cart method and its working fine.

<preference for="Magento\Checkout\Controller\Cart\Add" type="CustomPackage\Checkout\Controller\Magento\Checkout\Cart\Add" />

but i need to go through plugin so how can i do that ?
I seen some documentation and in plugin its used aroundExecute method.

so i don't understand that how my code execute without use Add method ? and how can i edit success message ?

I need to below message :

    $message = __('This Product has been added to your Shopping Cart. 
    Click here to view your <a href="%1">Shopping Cart</a>. 
    or you can <a href="%2">Continue Shopping.</a> <a href="javascript:void(0);" class="close-message">close</span>', $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl(),$this->_storeManager->getStore()->getBaseUrl());
    $this->messageManager->addSuccess($message);

any idea please share.

Best Answer

You can override the message template as this is a ComplexSuxxessMessage

$this->messageManager->addComplexSuccessMessage(
                            'addCartSuccessMessage',
                            [
                                'product_name' => $product->getName(),
                                'cart_url' => $this->getCartUrl(),
                            ]
                        );

So you have to put in your theme the following file

path: vendor/magento/module-checkout/view/frontend/templates/messages/addCartSuccessMessage.phtml

in your theme

app/design/frontend/Namespace/Theme/Magento_Checkout/templates/messages/addCartSuccessMessage.phtml

an change the message structure, you already have product_name and cart_url passed by the controller. I've added a wrapper arround in the example bellow.

<div class="add-to-cart-success-message">
        <?= $block->escapeHtml(__(
        'You added %1 to your <a href="%2">shopping cart</a>.',
        $block->getData('product_name'),
        $block->getData('cart_url')
    ), ["a"]); ?>
</div>
Related Topic