Search code examples
facebooktwittersharefacebook-opengraph

Multiple Facebook, Twitter share buttons in one page with custom image and title


I'm creating a blog where the landing page will show 5 latest posts by default and each post will have a Facebook and Twitter share buttons on them.

I will need each of the share button to have a default title, description and image attach to them and I'm using open graph to append the data.

The problem is how do I include multiple open graph data for each of the share button. I heard there is a way using iframe and another way is to pass the data in the share url.


Solution

  • Here is what I did.

    This code is for Twitter. Added once in HEAD html section:

    <script>window.twttr = (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0],
        t = window.twttr || {};
      if (d.getElementById(id)) return t;
      js = d.createElement(s);
      js.id = id;
      js.src = "https://platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js, fjs);
    
      t._e = [];
      t.ready = function(f) {
        t._e.push(f);
      };
    
      return t;
    }(document, "script", "twitter-wjs"));</script>
    

    This code is for Facebook. Added once at the top of the BODY html section.

    <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 = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    </script>
    

    The HTML for the homepage list with each item having it's own Twitter and FB buttons. Each referencing a the specific post page.

    <ul>
      <li>
        <h3>Post #1</h3>
        <div class="fb-share-button" data-href="https://example.com/post/1" 
             data-layout="button"></div>  
        <a href="https://twitter.com/share" class="twitter-share-button" 
           data-url="https://example.com/post/1">Tweet</a>
      </li>
      <li>
        <h3>Post #2</h3>
        <div class="fb-share-button" data-href="https://example.com/post/2" 
             data-layout="button"></div>  
        <a href="https://twitter.com/share" class="twitter-share-button" 
           data-url="https://example.com/post/2">Tweet</a>
      </li>
    </ul>