Social bookmarking buttons like Digg, Delicious or StumbleUpon on any website is very familiar. They help spreading the content.

Twitter, getting bigger & better, is also another powerful network where content can reach to thousands easily in minutes.

To help the readers of a website share/tweet a content at Twitter easily, here is a simple way of integration:

Twitter

You can send a querystring to Twitter like:

http://twitter.com/home?status=Your Tweet. For example, a tweet link for this post can be:

http://twitter.com/home?status=How To Add Tweeting With Short URL Functionality To A Website (With PHP): http://www.webresourcesdepot.com/how-to-add-tweeting-with-short-url-functionality-to-a-website-with-php/

The problem & the solution:

There is a 140 character limit in Twitter & the length of the URL is a headache. So, auto-shortening the URL with a short URL service will be handy.

The file_get_contents function of PHP helps us to easily get the short URL as a string. Lets use the TinyURL service & create a simple function:

<?php
function makeShortURL($URLToConvert) { 
     $shortURL= file_get_contents("http://tinyurl.com/api-create.php?url=" . $URLToConvert); 
     return $shortURL; 
}
?>

So, calling the function with the URL, like:

<?php echo makeShortURL("http://www.webresourcesdepot.com/how-to-add-tweeting-with-short-url-functionality-to-a-website-with-php/")?>

will result in: http://tinyurl.com/arbz2e.

And the link to this post will become:

http://twitter.com/home?status=How To Add Tweeting With Short URL Functionality To A Website (With PHP):http://tinyurl.com/arbz2e

For WordPress users:

Wordpress LogoWordPress users can add the makeShortURL function to the functions.php in the active theme folder.

Important, make sure you don’t leave any spaces between other functions & at the bottom of the functions.php file. Else, the RSS feed will have some trouble in creating the XML files.

And, in the single.php file, where the posts are displayed, use the line (or update it to your needs) below:

<a href="http://twitter.com/home?status=<?php the_title(); ?>: <?php echo makeShortURL(get_permalink())?>" rel="nofollow">Tweet This Post</a>.

And that’s all.

WebResourcesDepot Feed