Categories: Magento 2 Tutorials

How to Add Social Share Buttons in Magento 2

Social media platforms are one of the best ways to market a business in the age of digital media. Not only do you have a large number of audience present, but they are also active and contribute to promoting your business. And this is precisely the reason why social media is essential for all ecommerce stores. However, it would be much better if the customer shares your product themselves, and for them to do that, you have to give the customers an easy way to share the products on Social Media channels. Magento 2 is the leading ecommerce platform, but by default, it does not provide the option for customers to share products on social platforms. So today in this tutorial I am going to teach you how to add social sharing buttons in Magento 2 and show you how to integrate Facebook and Twitter button. Since editing core files are not recommended, I will use a custom module for this tutorial. If you don’t have any idea about using this method, you can refer to this guide: How to Create a Module in Magento 2.

Create Module

I am using Magenticians as Namespace and Mymodule as Module name. Create module.xml file in app/code/Magenticians/Mymodule/etc and paste this code in the file:
<?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="Magenticians_Mymodule" setup_version="2.0.0" />
</module>
</config>
Now register the module by creating registration.php in app/code/Magenticians/Mymodule and add this code in the file:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'Magenticians_Mymodule',
   __DIR__
);

Create Directories

Now create directories in the module as shown:

Copy and Override addtocart.phtml

Go to vendor/magento/module-catalog/view/frontend/templates/product/view and search addtocart.phtml file. Now copy this file in app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view. Now override the file by creating catalog_product_view.xml file in app/code/Magenticians/Mymodule/view/frontend/layout and add this code in the file:
<?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="product.info.addtocart">
           <action method="setTemplate">
               <argument name="template" xsi:type="string">Magenticians_Mymodule::catalog/product/view/addtocart.phtml</argument>
           </action>
       </referenceBlock>
   </body>
</page>

Add Social Sharing Buttons

For Facebook Go to Facebook for Developers and click on the Like Button, then scroll down to Like Button Configurator Section and click on Get Code: The screen with the code will show up; just copy the code from Step 1 and Step 2: Go to app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view/addtocart.phtml and create <div class=”social1”> in it and paste the code you copied above inside the div :
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/// @codingStandardsIgnoreFile
/** @var $block \Magento\Catalog\Block\Product\View */?>

<div class="social1">
<div id="fb-root"></div>
<script>
(
function(d, s, id) 
{
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) return;
 js = d.createElement(s); js.id = id;
 js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11';
 fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];  ?>" data-layout="standard" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div>
</div>

<?php $_product = $block->getProduct(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
<?php if ($_product->isSaleable()): ?>

<div class="box-tocart">
   <div class="fieldset">
       <?php if ($block->shouldRenderQuantity()): ?>
       <div class="field qty">
           <label class="label" for="qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></label>
           <div class="control">
               <input type="number"
                      name="qty"
                      id="qty"
                      value="<?= /* @escapeNotVerified */ $block->getProductDefaultQty() * 1 ?>"
                      title="<?= /* @escapeNotVerified */ __('Qty') ?>"
                      class="input-text qty"
                      data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                      />
           </div>
       </div>
       <?php endif; ?>
       <div class="actions">
           <button type="submit"
                   title="<?= /* @escapeNotVerified */ $buttonTitle ?>"
                   class="action primary tocart"
                   id="product-addtocart-button">
               <span><?= /* @escapeNotVerified */ $buttonTitle ?></span>
           </button>
           <?= $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>

<?php endif; ?>

<?php if ($block->isRedirectToCartEnabled()) : ?>

<script type="text/x-magento-init">
   {
       "#product_addtocart_form": 
{
           "Magento_Catalog/product/view/validation": 
{
               "radioCheckboxClosest": ".nested"
           }
       }
   }

</script>

<?php else : ?>

<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
           "Magento_Catalog/js/validate-product": {}
       }
   }
</script>
<?php endif; ?>
For Twitter Go to Twitter, scroll down the page and click on Twitter Buttons: Then click on Share Button: Once you get the twitter code; copy it: Go to app/code/Magenticians/Mymodule/view/frontend/templates/catalog/product/view/addtocart.phtml and create <div class=”social2”> in it and paste the twitter code inside of this div:
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/// @codingStandardsIgnoreFile
/** @var $block \Magento\Catalog\Block\Product\View */?>

<div class="social1">
<div id="fb-root"></div>
<script>(function(d, s, id) {
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) return;
 js = d.createElement(s); js.id = id;
 js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11';
 fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];  ?>" data-layout="standard" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div>
</div>

<div class="social2">
<a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

<?php $_product = $block->getProduct(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
<?php if ($_product->isSaleable()): ?>
<div class="box-tocart">
   <div class="fieldset">
       <?php if ($block->shouldRenderQuantity()): ?>
       <div class="field qty">
           <label class="label" for="qty"><span><?= /* @escapeNotVerified */ __('Qty') ?></span></label>
           <div class="control">
               <input type="number"
                      name="qty"
                      id="qty"
                      value="<?= /* @escapeNotVerified */ $block->getProductDefaultQty() * 1 ?>"
                      title="<?= /* @escapeNotVerified */ __('Qty') ?>"
                      class="input-text qty"
                      data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                      />
           </div>
       </div>
       <?php endif; ?>

       <div class="actions">
           <button type="submit"
                   title="<?= /* @escapeNotVerified */ $buttonTitle ?>"
                   class="action primary tocart"
                   id="product-addtocart-button">
               <span><?= /* @escapeNotVerified */ $buttonTitle ?></span>
           </button>
           <?= $block->getChildHtml('', true) ?>
       </div>
   </div>
</div>

<?php endif; ?>
<?php if ($block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
           "Magento_Catalog/product/view/validation": {
               "radioCheckboxClosest": ".nested"
           }
       }
   }
</script>
<?php else : ?>
<script type="text/x-magento-init">
   {
       "#product_addtocart_form": {
           "Magento_Catalog/js/validate-product": {}
       }
   }
</script>
<?php endif; ?>

Buttons Styling

Create newcss.css file in app/code/Magenticians/Mymodule/view/frontend/web/css and add this code in the file:
.social1
{
               margin-top: -40px;
}

.social2
{
           margin-top: 10px;
           margin-bottom: 5px;
}
To integrate the css file above, you need to update catalog_product_view.xml. So, go to app/code/Magenticians/Mymodule/view/frontend/layout/catalog_product_view.xml and update it with the following code:
<?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">

  <head>
        <css src="Magenticians_Mymodule::css/newcss.css"/>
   </head>

   <body>
       <referenceBlock name="product.info.addtocart">
           <action method="setTemplate">
               <argument name="template" xsi:type="string">Magenticians_Mymodule::catalog/product/view/addtocart.phtml</argument>
           </action>
       </referenceBlock>
   </body>
</page>
Run CLI Commands All done! Just run the following commands in the root directory of your store:
php bin/magento module:enable Magenticians_Mymodule
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:clean
php bin/magento cache:flush
It’s time to check the result. Go to the product page of your store and you will see the social sharing buttons:

Final Words

Giving your customers an option to share products on social media is a great and convenient marketing tactic. After following this guide, you should now be able to add social share buttons in Magento 2. Facing any issue related to this guide? Use the comment box below!
Syed Muneeb Ul Hasan

Syed Muneeb Ul Hasan is an expert in PHP and Magento, he prefers to educate users in implementing and learning Magento. When not working, he loves to watch cricket.

View Comments

  • i have used social sharing buttom on my client magento 2 site but there is an issue to connecting social site

  • Thanks for sharing! Is there anyway out to where we can include social sharing from CMS page? We have around 10 CMS pages where we have social sharing feature. How can we include these to CMS pages?

    Thanks.

  • Thanks for sharing about the social share extension. We tried this source code in magento 2.2 but unfortunately we got an error during module installation. Could you please help to resolve this error?

    Also we need Instagram integration. Is it possible?

    • Did you have run all the CLI commands which was mentioned in the post? And what is the error which you are facing?

      • Thanks for your reply. I can't run any CLI commands after Installation. I'm getting the below error:

        3 exception(s):
        Exception #0 (MagentoFrameworkExceptionLocalizedException): Invalid Document: C:xampphtdocshtmlappcodeMagenticiansMymoduleetcmodule.xml
        Error: DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 2 in C:xampphtdocshtmlvendormagentoframeworkXmlParser.php on line 161
        Exception #1 (MagentoFrameworkExceptionLocalizedException): DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 2 in C:xampphtdocshtmlvendormagentoframeworkXmlParser.php on line 161
        Exception #2 (MagentoFrameworkExceptionLocalizedException): DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 2 in C:xampphtdocshtmlvendormagentoframeworkXmlParser.php on line 161

        Please explain why am i getting this error. Looking forward to your suggestion.

        • I think you have done some mistake in your module.xml file, please try it again, Thanks!

          • Thanks. Now i can run all CLI commands succesfully. But now am getting the following error:

            1 exception(s):
            Exception #0 (MagentoFrameworkConfigDomValidationException): Element 'body': Character content other than whitespace is not allowed because the content type is 'element-only'.
            Line: 1129

            Element 'action': Character content other than whitespace is not allowed because the content type is 'element-only'.
            Line: 1133

            I've tried to make this correct using the suggestions from magento stack exchange but the issue has not been resolved. Please help me to resolve this!

          • I have removed the space before each tags. But still am getting an error. For checking purpose, i have uninstalled the module and now the site works without any issue. Please let me know further.

            If you could give me your personal email address that would be grateful.

          • Also i have one more query. Can you customize Instagram with this extension. Looking forward to your reply!

          • Can i have an update regarding whether we can connect Instagram with this extension?

Share
Published by
Syed Muneeb Ul Hasan

Recent Posts

Building Employee Trust and Dedication – A Complete Guide

In the highly competitive modern workplace, trust, and employee loyalty are crucial factors for long-term… Read More

3 months ago

12 Winning Strategies for Small Businesses Marketing

In the ever-evolving world of small business developing and implementing effective marketing strategies is critical to… Read More

3 months ago

Top 10 App Development Companies in Dubai 2024

With one of the highest internet penetration rates, the UAE has set out to revolutionize… Read More

3 months ago

Transforming Industries: How Amazons GPT44X is Revolutionizing AI Technology

Artificial Intelligence (AI) has been continually evolving, leading to remarkable advancements in various industries. Among… Read More

8 months ago

Top Magento 2 Extensions for 2023

Extensions, extensions and lots of extensions. We all love extensions, don’t we? After all, extensions… Read More

11 months ago

Unleashing the Power of Software Testing: Cooperating with a Testing Firm

Software quality is crucial to a firm's success across industries in the quickly changing digital… Read More

11 months ago