X

Facebook Share outside loop

Use Facebook share link outside the WordPress loop.

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

Code Snippet:

<?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 } ?>

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!