• Posted: 2010-11-15
  • Author: amit kosti
  • Tags:

Facebook Share outside loop

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
<?php
/*  you need separate single.php in your theme to work this if statement  */
if (is_single()) {
    /* This code is to show Facebook share link outside the wordpress loop */
    echo "<a href='http://www.facebook.com/sharer.php?u=";
    echo get_permalink($post->ID); // generates post url
    echo "&t=";
    echo the_title($post->title); // generates post title
    echo "' target='_blank' rel='nofollow'> Share on Facebook</a>";
    /* This is to show total number shares  */
    $url    = get_permalink($post->ID);
    $shares = json_decode(file_get_contents("http://api.facebook.com/method/fql.query?query=select%20share_count%20from%20link_stat%20where%20url='$url'&format=json"));
    echo $shares[0]->share_count;
}
/*  you need separate page.php to work this condition */
elseif (is_page()) {
    echo "<a href='http://www.facebook.com/sharer.php?u=";
    echo get_permalink($page->ID); // generate page url
    echo "&t=";
    echo the_title($page->title); // generate page title
    echo "' target='_blank' rel='nofollow'> Share on Facebook</a>";
    /* This is to show total number shares for page */
    $url    = get_permalink($page->ID);
    $shares = json_decode(file_get_contents("http://api.facebook.com/method/fql.query?query=select%20share_count%20from%20link_stat%20where%20url='$url'&format=json"));
    echo " - " . $shares[0]->share_count . " shares ";
} else {
    /* default Facebook share link or nothing  */
}
?>

<?php if (is_single()) { ?>
<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink($post->ID); ?>&t=<?php the_title($post->title); ?>" title="Share on Facebook" target="blank">Share on Facebook</a> -
<?php } ?>

Instructions:

It might be difficult to show Facebook share link outside the WordPress loop, since you can’t retrieve post information the usual way. To show a Facebook share link in the sidebar of single post, this snippet will be useful. This will also show how many time the url was shared on Facebook.

The last snippet is the short code ( it only works with single posts, so use conditional if statement ).

NOTES :

1. This is useful to show text link only, If you want to show buttons then you must use ready made script from Facebook.

2. Make sure you have page.php and single.php template otherwise it won’t work

3. To show facebook share link into the wordpress loop use this snippet By Filip Stefansson


Share this snippet

If you like this snippet, share it with friends!