While creating the new version of Slimmity i decided not to use a plugin for the social links. After reading a post over at ThemeForest's blog i decided to include the code directly in my theme, all was good until i got to the twitter button, that's where it got a bit complicated. Well not exactly complicated, but wasn't realy what i was looking for.

But the problem about the function on the ThemeForest Blog post was that it will generate a new short url each time there was a new visit or if someone refreshed the page. So there had to be a cache system of some sort added. After reading the comments on ThemeForest blog post i came across this german blog that uses bit.ly and stores the new shortened url in a custom field associated with the post. But this still wasn't exactly what i wanted. It used the API but not in the correct way.

So i started off with the code i got from the german blog and read the bit.ly api documentation and from that i got the first function that shortens the url we provide.

function shorten_url($login,$appkey,$url,$format = 'xml') {
	$bitly = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.$url.'&login='.$login.'&apiKey='.$appkey.'&format='.$format; // Bitly Api request
	$response = file_get_contents($bitly); // Get the file content of the api request
	if(strtolower($format) == 'json') { // Use JSON to parse the request
		$json = @json_decode($response,true);
		return $json['results'][$url]['shortUrl'];
	}
	else { // use xml to parse the request
		$xml = simplexml_load_string($response);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

The usage of this function is simple: shorten_url(bitlylogin,bitlyapikey,http://slimmity.com/realy-long-url-for-testing/,json) the first the attributes we input are pretty self explanitory but the last one "json" might be confusing. What this does is pick whether we want to parse the results with either XML or JSON, if you wish just don't specify the parse format and it will use xml by default.

Now that we have the function that will shorten our url we have to make the function that will store this value in a custom field.

function save_bitly_url($bitlylogin,$bitlyapikey,$id) {
	$url = shorten_url($bitlylogin,$bitlyapikey,get_permalink($id)); // we shorten our posts permalink
	if (!$url) {
		$url = sprintf('%s?p=%s',get_bloginfo('url'),$id); // if we have an error while shortening the url we use wordpress default http://slimmity.com/?p=12
	}
	add_post_meta($id,'bitly_url',$url); // We store our new shortened link or wordpress url in a custom field related to our post
	return $url; // We return the url to be used
}

Now that we have created and saved our brand new short url we have to display the twitter link. We do that with yet another function (I promise its the last one).

function get_twitter_msg($bitlylogin,$bitlyapikey) {
	if (!$url = get_post_meta(get_the_ID(), 'bitly_url', true)) { // We try and see if we have a saved short url
		$url = save_bitly_url($bitlylogin,$bitlyapikey,get_the_ID()); // if not we make a new one
	}
	echo sprintf('http://twitter.com/home?status=%s%s%s%s',urlencode('RT @Slimmity '),urlencode(get_the_title()),urlencode(' - '),$url); // We echo our link to be used
}

In the last function we use "urlencode" so all the spaces we leave between words are converted to the symbol "+". So our final use of these 3 functions would be

<a href="<?PHP get_twitter_msg(yourbitlylogin,yourbitlyapikey); ?>">Tweet This!</a>

For the lazy ones heres the 3 functions together

function shorten_url($login,$appkey,$url,$format = 'xml') {
	$bitly = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.$url.'&login='.$login.'&apiKey='.$appkey.'&format='.$format; // Bitly Api request
	$response = file_get_contents($bitly); // Get the file content of the api request
	if(strtolower($format) == 'json') { // Use JSON to parse the request
		$json = @json_decode($response,true);
		return $json['results'][$url]['shortUrl'];
	}
	else { // use xml to parse the request
		$xml = simplexml_load_string($response);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}
function save_bitly_url($bitlylogin,$bitlyapikey,$id) {
	$url = shorten_url($bitlylogin,$bitlyapikey,get_permalink($id)); // we shorten our posts permalink
	if (!$url) {
		$url = sprintf('%s?p=%s',get_bloginfo('url'),$id); // if we have an error while shortening the url we use wordpress default http://slimmity.com/?p=12
	}
	add_post_meta($id,'bitly_url',$url); // We store our new shortend link or wordpress url in a custom field related to our post
	return $url; // We return the url to be used
}
function get_twitter_msg($bitlylogin,$bitlyapikey) {
	if (!$url = get_post_meta(get_the_ID(), 'bitly_url', true)) { // We try and see if we have a saved short url
		$url = save_bitly_url($bitlylogin,$bitlyapikey,get_the_ID()); // if not we make a new one
	}
	echo sprintf('http://twitter.com/home?status=%s%s%s%s',urlencode('RT @Slimmity '),urlencode(get_the_title()),urlencode(' - '),$url); // We echo our link to be used
}

Don't forget to change @Slimmity for your twitter account.

Ass you can see this tutorial is simple and get the job done, but if you just don't want to be bothered you can use a plugin, one of the most popular ones out there right now is the Tweetmeme Plugin, or you can consider one of these.

6 Comments so far Leave your own

  1. daniella
    20 Nov, 2009

    Yeah baby!

  2. Cleothildee
    24 Nov, 2009

    i love to Twitter my day to day activities to my friends and followers. Twitter is much better than blogging because it is direct to the point and does not require you to type so many unnecessary words. Great tutorial!

  3. Hyder
    3 Dec, 2009

    Hi,

    Thanks for the tut. I get an error though, undefined function for this line:

    $xml = simplexml_load_string($response);

    Any thoughts?

  4. Omar
    3 Dec, 2009

    Well if your trying out the code on localhost this could be of how your php.ini is setup. As for it works i am completly sure it does because its the actual code i am using on this blog to manage my twitter links.

  5. Earl Jones
    27 May, 2010

    Awesome! You rock!

  6. Marketer Joe
    13 Aug, 2010

    Quite a complex script, mate, but thanks for sharing it with us!
    Perhaps I will understand it, as I go through it thoroughly…

    Thanks!

Post Your Comment