Storing bit.ly links against wordpress posts. Posted on: May 18, 2012

When it comes to creating websites these days, one can't avoid including social media links for sharing. Twitter's good old 140 character limit on tweets has caused issues when it comes to using really long urls for me, so I've come to using the following:

/* Get the bit.ly link for a url. If the link has already been created, get it from the post meta instead of making a curl request for every page load. */
function bitly($_link) {
	global $post;
	if (empty($_link)) $_link = get_permalink($post->ID);
	$_existing = get_post_meta($post->ID, 'bitly', true);
	if ($_existing !== false && !empty($_existing)) return $_existing;
	$_link = curl_get_result('http://api.bit.ly/v3/shorten?login=YOUR_LOGIN&apiKey=YOUR_API_KEY&longUrl='.urlencode($_link).'&format=txt');
	update_post_meta($post->ID, 'bitly', $_link);
	return $_link;
}

/* returns a result from url */
function curl_get_result($url) {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

This creates a bit.ly link for the current post or for the link you pass in (if it doesn't exist already) and stores it in a post meta field for the post (so that we don't bombard bit.ly on every page load). If you chuck this in your functions.php file, using it is as simple as follows:

<a title="some link description here" href=<?php echo bitly(); ?>">some link description here</a>