Here we have developed a Magento 2 Newsletter Subscription extension that helps you to add gender-wise subscription functionality to your Magento 2 store.
Wishusucess_Newsletter Magento 2 extension developed by Wishusucess expert Magento 2 Team.
So this newsletter module will add a great experience to your shopping store and when your customer visits your site then they can subscribe to your newsletter based on their gender. So you can notify your customers based on their gender and can increase more seals. you will also be able to provide them special offer about a particular product to your customer on your Magento 2 store.
Create Custom Magento 2 Newwsletter Suibscription
app/code/Wishusucess/Newsletter/registration.php
app/code/Wishusucess/Newsletter/etc/module.xml
app/code/Wishusucess/Newsletter/etc/di.xml
app/code/Wishusucess/Newsletter/Setup/InstallSchema.php
app/code/Wishusucess/Newsletter/Controller/Subscribe/NewAction.php
app/code/Wishusucess/Newsletter/Block/Subscribe.php
app/code/Wishusucess/Newsletter/Model/Subscriber.php
app/code/Wishusucess/Newsletter/view/adminhtml/layout/newsletter_subscriber_block.xml
app/code/Wishusucess/Newsletter/view/frontend/layout/default.xml
app/code/Wishusucess/Newsletter/view/frontend/templates/subscribe.phtml
Turn off Magento 2 Newsletter Subscription
So when you don't need this feature then you will also be able to turn off these custom newsletter_subscription features from your admin.
In order to turn off, these features just go to the Magento admin and click
Stores -> Configuration -> Customers -> Newsletter Tab
and then choose your setting like set to disable if you don't need it to need then turns on this feature by setting enable newsletter.
Register Magento 2 Newsletter Module
app/code/Wishusucess/Newsletter/registration.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Wishusucess_Newsletter', __DIR__ );
Define Basic Information of Newsletter
app/code/Wishusucess/Newsletter/etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Wishusucess_Newsletter" setup_version="1.0.0"/> <sequence> <module name="Magento_Newsletter" /> </sequence> </config>
Decide Preferences Through Dependency Injection
So here you will be able to decide your newly added class and then you have to give the preferences in the di.xml file.
app/code/Wishusucess/Newsletter/etc/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\Newsletter\Controller\Subscriber\NewAction" type="Wishusucess\Newsletter\Controller\Subscribe\NewAction" /> <preference for="Magento\Newsletter\Model\Subscriber" type="Wishusucess\Newsletter\Model\Subscriber" /> </config>
Add Column Gender in Magento 2 Newsletter Table
So here you can add the custom column which is gender in Magento 2 newsletter_subscriber database table.
app/code/Wishusucess/Newsletter/Setup/InstallSchema.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ namespace Wishusucess\Newsletter\Setup; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\DB\Ddl\Table; class InstallSchema implements InstallSchemaInterface { public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $table = $setup->getTable('newsletter_subscriber'); $setup->getConnection()->addColumn( $table, 'gender', [ 'type' => Table::TYPE_INTEGER, 'nullable' => true, 'comment' => 'Gender' ] ); $setup->endSetup(); } }
Create Controller For Magento 2 Newsletter
So here execute() method processed over the newly added column gender Magento 2 newsletter subscription. So you can decide the action which you have to perform over this column.
app/code/Wishusucess/Newsletter/Controller/Subscribe/NewAction.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ namespace Wishusucess\Newsletter\Controller\Subscribe; use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement; use Magento\Customer\Model\Session; use Magento\Customer\Model\Url as CustomerUrl; use Magento\Framework\App\Action\Context; use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; use Magento\Framework\Validator\EmailAddress as EmailValidator; use Magento\Newsletter\Controller\Subscriber as SubscriberController; use Magento\Newsletter\Model\Subscriber; use Magento\Newsletter\Model\SubscriptionManagerInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Newsletter\Model\SubscriberFactory; class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction { /** * @var CustomerAccountManagement */ protected $customerAccountManagement; /** * @var EmailValidator */ private $emailValidator; /** * @var SubscriptionManagerInterface */ private $subscriptionManager; /** * Initialize dependencies. * * @param Context $context * @param SubscriberFactory $subscriberFactory * @param Session $customerSession * @param StoreManagerInterface $storeManager * @param CustomerUrl $customerUrl * @param CustomerAccountManagement $customerAccountManagement * @param SubscriptionManagerInterface $subscriptionManager * @param EmailValidator $emailValidator */ public function __construct( Context $context, SubscriberFactory $subscriberFactory, Session $customerSession, StoreManagerInterface $storeManager, CustomerUrl $customerUrl, CustomerAccountManagement $customerAccountManagement, SubscriptionManagerInterface $subscriptionManager, EmailValidator $emailValidator = null ) { $this->customerAccountManagement = $customerAccountManagement; $this->subscriptionManager = $subscriptionManager; $this->emailValidator = $emailValidator ?: ObjectManager::getInstance()->get(EmailValidator::class); parent::__construct( $context, $subscriberFactory, $customerSession, $storeManager, $customerUrl, $customerAccountManagement, $subscriptionManager, $emailValidator ); } public function execute() { if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) { $gender = $this->getRequest()->getPost('gender'); $email = (string)$this->getRequest()->getPost('email'); try { $this->validateEmailFormat($email); $this->validateGuestSubscription(); $this->validateEmailAvailable($email); $websiteId = (int)$this->_storeManager->getStore()->getWebsiteId(); /** @var Subscriber $subscriber */ $subscriber = $this->_subscriberFactory->create()->loadBySubscriberEmail($email, $websiteId); if ($subscriber->getId() && (int)$subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED) { throw new LocalizedException( __('This email address is already subscribed.') ); } $storeId = (int)$this->_storeManager->getStore()->getId(); $currentCustomerId = $this->getSessionCustomerId($email); $subscriber = $currentCustomerId ? $this->subscriptionManager->subscribeCustomer($currentCustomerId, $storeId) : $this->subscriptionManager->subscribe($email, $storeId); // add gender data to the model $subscriber->setData('gender',$gender); $subscriber->save(); $message = $this->getSuccessMessage((int)$subscriber->getSubscriberStatus()); $this->messageManager->addSuccessMessage($message); } catch (LocalizedException $e) { $this->messageManager->addComplexErrorMessage( 'localizedSubscriptionErrorMessage', ['message' => $e->getMessage()] ); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('Something went wrong with the subscription.')); } } /** @var Redirect $redirect */ $redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $redirectUrl = $this->_redirect->getRedirectUrl(); return $redirect->setUrl($redirectUrl); } /** * Get customer id from session if he is owner of the email * * @param string $email * @return int|null */ private function getSessionCustomerId(string $email): ?int { if (!$this->_customerSession->isLoggedIn()) { return null; } $customer = $this->_customerSession->getCustomerDataObject(); if ($customer->getEmail() !== $email) { return null; } return (int)$this->_customerSession->getId(); } /** * Get success message * * @param int $status * @return Phrase */ private function getSuccessMessage(int $status): Phrase { if ($status === Subscriber::STATUS_NOT_ACTIVE) { return __('The confirmation request has been sent.'); } return __('Thank you for your subscription.'); } }
Create Block for Magento 2 Newsletter Subscription
Now you can retrieve the form action URL and set the "secure" param to avoid confirmation. and you also decide what message you want to show when action submits the form from a secure page to unsecure.
app/code/Wishusucess/Newsletter/Block/Subscribe.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ namespace Wishusucess\Newsletter\Block; use Magento\Framework\View\Element\Template; class Subscribe extends \Magento\Framework\View\Element\Template { /** * Retrieve form action url and set "secure" param to avoid confirm * message when we submit form from secure page to unsecure * * @return string */ public function getFormActionUrl() { return $this->getUrl('newsletter/subscriber/new', ['_secure' => true]); } } /*class Subscribe extends Template { public function __construct(Template\Context $context,array $data = []) { parent::__construct($context, $data); } public function beforeToHtml(\Magento\Newsletter\Block\Subscribe $originalBlock){ $originalBlock->setTemplate('BDC_Newsletter::subscribe.phtml'); } }*/
Model Class in Newsletter Subscription
app/code/Wishusucess/Newsletter/Model/Subscriber.php
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ namespace Wishusucess\Newsletter\Model; class Subscriber extends \Magento\Newsletter\Model\Subscriber { /** * Initialize resource model * * @return void */ public function subscribe($email) { echo "=----------->";exit; $this->loadByEmail($email); if (!$this->getId()) { $this->setSubscriberConfirmCode($this->randomSequence()); } $isConfirmNeed = $this->_scopeConfig->getValue( self::XML_PATH_CONFIRMATION_FLAG, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ) == 1 ? true : false; $isOwnSubscribes = false; $isSubscribeOwnEmail = $this->_customerSession->isLoggedIn() && $this->_customerSession->getCustomerDataObject()->getEmail() == $email; if (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED || $this->getStatus() == self::STATUS_NOT_ACTIVE ) { if ($isConfirmNeed === true) { // if user subscribes own login email - confirmation is not needed $isOwnSubscribes = $isSubscribeOwnEmail; if ($isOwnSubscribes == true) { $this->setStatus(self::STATUS_SUBSCRIBED); } else { $this->setStatus(self::STATUS_NOT_ACTIVE); } } else { $this->setStatus(self::STATUS_SUBSCRIBED); } $this->setSubscriberEmail($_POST['email']); } if(!empty($_POST['subscriber_name']) ){ $this->setSubscriberName($_POST['subscriber_name']); //subscriber_name $this->setSubscriberDateofbirth($_POST['subscriber_dateofbirth']); //date of birth $this->setSubscriberCountrycode($_POST['subscriber_countrycode']); //country code } if ($isSubscribeOwnEmail) { try { $customer = $this->customerRepository->getById($this->_customerSession->getCustomerId()); $this->setStoreId($customer->getStoreId()); $this->setCustomerId($customer->getId()); } catch (NoSuchEntityException $e) { $this->setStoreId($this->_storeManager->getStore()->getId()); $this->setCustomerId(0); } } else { $this->setStoreId($this->_storeManager->getStore()->getId()); $this->setCustomerId(0); } $this->setStatusChanged(true); try { $this->save(); if ($isConfirmNeed === true && $isOwnSubscribes === false ) { $this->sendConfirmationRequestEmail(); } else { $this->sendConfirmationSuccessEmail(); } return $this->getStatus(); } catch (\Exception $e) { throw new \Exception($e->getMessage()); } } }
Adminhtml Layout XML File
app/code/Wishusucess/Newsletter/view/adminhtml/layout/newsletter_subscriber_block.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="adminhtml.newslettrer.subscriber.grid.columnSet"> <block class="Magento\Backend\Block\Widget\Grid\Column"> <arguments> <argument name="header" xsi:type="string" translate="true">Gender</argument> <argument name="index" xsi:type="string">gender</argument> <argument name="type" xsi:type="string">options</argument> <argument name="options" xsi:type="array"> <item name="gender_male" xsi:type="array"> <item name="value" xsi:type="string">1</item> <item name="label" xsi:type="string" translate="true">Male</item> </item> <item name="gender_female" xsi:type="array"> <item name="value" xsi:type="string">2</item> <item name="label" xsi:type="string" translate="true">Female</item> </item> <item name="gender_not_specified" xsi:type="array"> <item name="value" xsi:type="string">3</item> <item name="label" xsi:type="string" translate="true">Not Specified</item> </item> </argument> <argument name="header_css_class" xsi:type="string">col-gender</argument> <argument name="column_css_class" xsi:type="string">ccol-gender</argument> </arguments> </block> </referenceBlock> </body> </page>
Frontend Layout Component in Newsletter
Now we to call the component.phtml file in this default.xml so this will show everywhere of Magento 2 stores.
app/code/Wishusucess/Newsletter/view/frontend/layout/default.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="head.components"> <block class="Magento\Framework\View\Element\Js\Components" name="newsletter_head_components" template="Magento_Newsletter::js/components.phtml"/> </referenceBlock> <!--referenceContainer name="footer"> <block class="Magento\Newsletter\Block\Subscribe" name="form.subscribe" as="subscribe" before="-" template="Magento_Newsletter::subscribe.phtml"/> </referenceContainer--> <!-- <referenceContainer name="footer"> <referenceBlock name="form.subscribe" remove="true"/> <block class="BDC\Newsletter\Block\Subscribe" name="form.custom.subscribe" before="-" template="BDC_Newsletter::subscribe.phtml"/> <block class="BDC\Newsletter\Block\Review" name="review.list" template="right-review.phtml"> <block class="Magento\Newsletter\Block\Subscribe" name="review_list_pager" as="review_list_pager"/> </block> </referenceContainer> --> </body> </page>
Get Data Of Newsletter Subscription in Magento 2
Here is how you want to show the data on the front end you can decide now your newsletter_subscription extension will show the data of the extra column of the newsletter_subscription table.
app/code/Wishusucess/Newsletter/view/frontend/templates/subscribe.phtml
<?php /* * @Author Hemant Singh * @Developer Hemant Singh * @Module Wishusucess_Newsletter * @copyright Copyright (c) Wishusucess (http://www.wishusucess.com/) */ ?> <div class="block newsletter"> <div class="title"><strong><?php /* @escapeNotVerified */ echo __('Newsletter') ?></strong></div> <div class="content"> <form class="form subscribe" novalidate action="<?php echo $block->escapeUrl($block->getFormActionUrl()) ?>" method="post" data-mage-init='{"validation": {"errorClass": "mage-error"}}' id="newsletter-validate-detail"> <div class="field firstname"> <label class="label" for="firstname"><span><?php echo $block->escapeHtml(__('First Name')) ?></span></label> <div class="control"> <input name="firstname" type="text" id="firstname" placeholder="<?php echo $block->escapeHtmlAttr(__('First Name')) ?>" data-validate="{required:true}"/> </div> </div> <div class="field lastname"> <label class="label" for="lastname"><span><?php echo $block->escapeHtml(__('Last Name')) ?></span></label> <div class="control"> <input name="lastname" type="text" id="lastname" placeholder="<?php echo $block->escapeHtmlAttr(__('Last Name')) ?>" data-validate="{required:true}"/> </div> </div> <?php $_gender = $block->getLayout()->createBlock('Magento\Customer\Block\Widget\Gender') ?> <?php echo $_gender->toHtml() ?> <div class="field newsletter"> <label class="label" for="newsletter"><span><?php echo $block->escapeHtml(__('Sign Up for Our Newsletter:')) ?></span></label> <div class="control"> <input name="email" type="email" id="newsletter" placeholder="<?php echo $block->escapeHtmlAttr(__('Enter your email address')) ?>" data-validate="{required:true, 'validate-email':true}"/> </div> </div> <div class="actions"> <button class="action subscribe primary" title="<?php echo $block->escapeHtmlAttr(__('Subscribe')) ?>" type="submit"> <span><?php echo $block->escapeHtml(__('Subscribe')) ?></span> </button> </div> </form> </div> </div>
Now, Run Following Command:
php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento setup:static-content:deplpy -f php bin/magento cache:clean
Download Link:
Wishusucess Newsletter_Subscription Extension in Magento 2
Hire Magento 2 Expert Developer to Develop Your Store
Related Post:
Custom Shipping Text Filed: Show Custom Text Magento 2
Search AutoComplete: Magento 2 Module Add All Category for Search
Share Product on WhatsApp: With Products Image And URL in Magento 2
Recommended Post:
Magento 2.4 Installation Guide: How to Install Magento 2.4.2
Magento Store: Best 36 Magento Websites Example in The World
SEO Packages: How Much Do SEO Packages Cost in India, SEO Pricing