If you have “Share This Post” links on your Wordpress blog posts, you probably need to automatically display shortened urls. While there are a few different techniques out there, I’ve found this particular one to be the easiest and most effective.
We will make use of the wonderful bit.ly service to accomplish this task. Before you start with the tutorial, you must first register and activate your account on bit.ly. Remember your username and copy your API Key from the account page. Now let’s get started.
1. Set It Up
Place the following code in functions.php (for Thesis users: custom_functions.php).
function getBitlyUrl($url) {
$bitlylogin = 'YOUR LOGIN NAME';
$bitlyapikey= 'YOUR API KEY';
$bitlyurl = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitlylogin."&apiKey=".$bitlyapikey);
$bitlycontent = json_decode($bitlyurl,true);
$bitlyerror = $bitlycontent["errorCode"];
if ($bitlyerror == 0) {
$bitlyurl = $bitlycontent["results"][$url]["shortUrl"];
}
else $bitlyurl = "error";
return $bitlyurl;
}
With that in place, you must now locate the function that houses your social media links. If you haven’t already created a social media sharing box, I have two different tutorials (here & here) that can help you do just that.
2. Make It Work
Within that function, place this code near the top.
$burl = getBitlyUrl(get_permalink($post->ID));
Next, place this wherever you would like the link to display or activate.
<?php echo $burl; ?>
For example, to create a single link that will automatically (1) post to Twitter using the (2) bit.ly url at the (3) bottom of single posts, you would use the following code (for Thesis Users only, but easily adaptable for other themes).
function twitter_share() {
$burl = getBitlyUrl(get_permalink($post->ID)); ?>
<a href="http://twitter.com/home?status=Check This Out: <?php echo $burl; ?>">Share on Twitter</a>
<?php }
add_action('thesis_hook_after_post', 'twitter_share');
If you don’t understand php, this tutorial might seem a little advanced. I encourage you to try it yourself, but only if you backup custom_functions.php and have easy access to your site’s ftp.
