Web Masters Site All For Web Masters

16May/100

How to Automatically Create Bit.ly Links for Blog Posts

URL Shortner services used to trim down your long urls to a short and easy to share links. This code will automatically generate Bit.ly short links for your blog posts for easy to share on Twitter and IMs.
Open functions.php file of your theme and add the following code:

function bitlyLink($url) {
 
$username = "Bit.ly Username"; // Your Bit.ly Username
$api = "Bit.ly API Key"; // Your Bit.ly API Key
 
$data = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=".$url."&login=".$username."&apiKey=".$api);
 
$xml = new SimpleXMLElement($data);
$shortlink = $xml->results->nodeKeyVal->shortUrl;
 
return $shortlink;
}

Don’t forget to add your Bit.ly Username and API key (get API key)

Now add the following code within loop in single.php file of your theme.

<?php
$bitlyLink = bitlyLink(get_permalink($post->ID));
echo 'Short Link for this post: <a href="'.$bitlyLink.'">'.$bitlyLink.'</a>'
?>

P.S. All the links will generate within your account so you can track them all by logging in to your Bit.ly account.

Open functions.php file of your theme and add the following code:

01 function bitlyLink($url) {
02
03 $username = "Bit.ly Username"; // Your Bit.ly Username
04 $api = "Bit.ly API Key"; // Your Bit.ly API Key
05
06 $data = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=".$url."&login=".$username."&apiKey=".$api);
07
08 $xml = new SimpleXMLElement($data);
09 $shortlink = $xml->results->nodeKeyVal->shortUrl;
10
11 return $shortlink;
12 }

Don’t forget to add your Bit.ly Username and API key (get API key)

Now add the following code within loop in single.php file of your theme.

1 <?php
2 $bitlyLink = bitlyLink(get_permalink($post->ID));
3 echo 'Short Link for this post: <a href="'.$bitlyLink.'">'.$bitlyLink.'</a>'
4 ?>

P.S. All the links will generate within your account so you can track them all by logging in to your Bit.ly account.

Filed under: Wordpress Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

 

No trackbacks yet.