Search code examples
javascriptfacebookfacebook-graph-apifacebook-opengraphsharing

How to Facebook share a single blog post, rather than the entire blog feed


I'm hoping my question isn't stupid, I'm very new with Javascript.

I've created a Facebook share button by using a script directly from Facebook:

<a href="#" 
  onclick="
    window.open(
      'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href), 
      'facebook-share-dialog', 
      'width=626,height=436'); 
    return false;">
  Share on Facebook
</a>

However, when I click the link, it wants to share the entire URL of my blog, rather than just the specific blog post. I have read other people suggesting something about Open Graph, but am unsure how this relates. Any help would be awesome.


Solution

  • The key is to replace location.href with that blog post's specific URL.

    If you use Wordpress, you can add into The Loop something like this:

    <a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(<?php the_permalink(); ?>), 'facebook-share-dialog', 'width=626,height=436'); return false;">Share on Facebook</a>
    

    In Wordpress, the_permalink() will return the exact URL for that post, ensuring that Facebook will only share that specific post.