Using Bitly URLs in WordPress and use them with Twitter and GooglePlus Scripts

Step 1 Preparing The Code

Login to your bitly account. If you don’t have one, it takes only a minute to setup your account. After logging into your account, go to the settings page, scroll down almost half the way and copy your API. We’ll be using this in a minute or so.
api

Step 2 Modifying Your functions.php

Copy the code below and paste it in your functions file. (Although the code is straightforward, I have added comments in the code so as to make it easier to understand).

//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'USERNAME-HERE'; //your bit.ly login
$apikey = 'API-HERE'; //add your bit.ly API
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;

//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}

Step 3 Adding Twitter and +1 buttons

Now you are familiar with the code and how to use this, let’s benefit from the code and see some examples for inspiration and encouragement. Below are examples of this code being used with Twitter and Google Plus that I use on my blog.

The first one is of twitter and the code shows the size of the button and the links to suggested people.

<a href="http://twitter.com/share?url=<?php echo urlencode( bitly()); ?>&counturl=<?php urlencode(the_permalink()); ?>" class="twitter-share-button" data-count="horizontal" data-via="USERNAME-HERE">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

You can copy the above code or you can go to Twitter and design the code as you like. Remember to change the “data-via” type. Notice the urlencode function is passed the newly created bitly function.

For Google Plus, copy the code below. If you want a more customized code, then go to Google+ and design the +1 button as per your liking. Notice how I have changed the code to incorporate bitly function.

<g:plusone size=”medium” href=”<? bitly(); ?>”></g:plusone>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s