Magento 2 Tutorials

How to Add Social Share Buttons in Magento 2

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:

directories social share buttons Magento 2

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:

get code fb

The screen with the code will show up; just copy the code from Step 1 and Step 2:

fb button code

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:

click twitter buttons

Then click on Share Button:

share tweet

Once you get the twitter code; copy it:

copy twitter button code

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:

result social share magento 2

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!

Subscribe Newsletter

Subscribe to get latest Magento news

40% Off for 4 Months on Magento Hosting + 30 Free Migration