How to Add Custom Field in Newsletter Subscription in magento2 - Magento source24


Hello magento friends todays in this blog post im share with you to How to Add Custom Field in Newsletter Subscription in magento2 . To add a custom field to the newsletter subscription form in Magento 2, you'll need to perform a series of steps. These steps involve creating a new module and modifying certain files to achieve your goal. Here's a general outline of the process:


➤ Create a New Module:

First, create a new custom module or use an existing one. Let's call it Custom_Newsletter.


Create the Required Files and Directories:

Inside your module directory, create the necessary files and directories in the following structure:


app/code/Custom/Newsletter/

├── registration.php

├── etc

│   ├── module.xml

│   ├── frontend

│   │   ├── di.xml

│   │   └── events.xml

│   └── extension_attributes.xml

└── Block

    └── Newsletter

        └── Subscribe.php


➤ Define Your Custom Field:

Edit the app/code/Custom/Newsletter/etc/frontend/di.xml file to add your custom field to the newsletter subscription form. Add the following code:


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Newsletter\Model\Subscriber">
        <plugin name="custom_newsletter_subscriber_plugin" type="Custom\Newsletter\Plugin\SubscriberPlugin"/>
    </type>
</config>


➤Create the Plugin Class:

Create the plugin class that will handle adding the custom field value to the subscriber object.

Create app/code/Custom/Newsletter/Plugin/SubscriberPlugin.php with the following content:


How to Add Custom Field in Newsletter Subscription in magento2 - Magento source24



➤Modify the Newsletter Subscription Form:

Edit the file app/design/frontend/{Vendor}/{Theme}/Magento_Newsletter/templates/subscribe.phtml to add the HTML for your custom field in the newsletter subscription form. For example:


How to Add Custom Field in Newsletter Subscription in magento2 - Magento source24


➤Handle Form Data:

Modify the subscribe.phtml file to include the custom field in the form submission.

➤Run Setup and Clear Cache:

Run the following commands to enable the module and clear the cache:


php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush


Now your Magento 2 store should have a custom field in the newsletter subscription form, and the data entered in that field will be saved in the subscriber object. Make sure to adjust the code snippets according to your specific needs and structure.




Deepak Kumar Bind

Success is peace of mind, which is a direct result of self-satisfaction in knowing you made the effort to become the best of which you are capable.

Post a Comment

If you liked this post please do not forget to leave a comment. Thanks

Previous Post Next Post