WordPress: adding social buttons with iframes

JavaScript social buttons are evil. They may cause major hiccups in the overall performance of your sites, not to mention that they may actually block the rendering of your pages. Iframes are better, because they load simple HTML snippets. In this post I'll show you how to add the Twitter, Facebook and Google Plus buttons to your WordPress theme.

Add the following code to the functions.php file of your theme (create one if it doesn't exist):

function tweet_button() {

 $title = get_the_title();
 $link = get_permalink();
 
 $html = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?';
 $html .= 'url=' . $link . '&text=' . $title . '&count=vertical&via=username"></iframe>';
 
 return $html;

}

function facebook_button() {

 $title = get_the_title();
 $link = get_permalink();
 
 $html = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://www.facebook.com/plugins/like.php?';
 $html .= 'href=' . $link . '&title=' . $title . '&layout=box_count"></iframe>';
 
 return $html;

}


function google_plus_button() {

 $link = get_permalink();
 
 $html = '<iframe src="https://plusone.google.com/u/0/_/+1/fastbutton?url=';
 $html .= $link . '&size=tall&count=true&annotation=bubble&lang=it" scrolling="no" frameborder="0"></iframe>';
 
 return $html;

}

Then you can use such functions directly in your theme files, as follows:

<div id="social">
 <span class="twitter"><?php echo tweet_button();?></span>
 <span class="facebook"><?php echo facebook_button();?></span>
 <span class="google-plus"><?php echo google_plus_button();?></span>
</div>

Bear in mind that the above functions must be called in The Loop.

Leave a Reply

Note: Only a member of this blog may post a comment.