19
2010
Share Feedback with Twitter and the Bit.ly API
Regular blog readers probably notice the wide range of social media “Share this” links found on most sites. With everyone from CNN to ESPN integrating ways of sharing content, one of the most popular techniques is using a URL shortener to neaten up and condense the link.
Today we’re going to explore this idea of sharing content a little bit more. Sharing links to content is just one piece of the social media equation. Capturing the response to it is quite another.
Let’s get started:
What We’re Building
Today’s tutorial will walk through the creation of a customizable “Tweet this” link that integrates the Bit.ly API and Twitter updates. The goal will be to have a selectable menu of prefaces, and then tweet the preface and link accordingly. Here are some examples of possible end results:
- Reading: Article Name / Article Link
- I absolutely loved: Article Name / Article Link
- Made me think: Article Name / Article Link
- Completely disagree: Article Name / Article Link
- Article Name / Article Link
What’s the point?
This way a reader will be able to add some personality to the shared link, rather than sticking to a rigid “Currently Reading” preface like the one this blog is (currently) guilty of*. People respond to content differently, and this is a kind of system that helps them share it easily. If I found a post thought-provoking, I’d like to say so. On the flip side, you (as the site owner) will be able to see what kind of feedback people are giving about your content. Think of it like an indirect polling system.
I haven’t seen this kind of Twitter feedback system done anywhere else with blogs yet, but then again the internet is a big place. Now that we’ve all got our eyes on the same prize, let’s get introduced to the API’s we’ll be working with:
*For those wondering, yes, this will be part of the upcoming Build Internet theme update.
The Bit.ly API
The Bit.ly Developer Tools allow you to take a URL and return the new shortened link. It sounds simple because it is. This also means that working with the API is surprisingly pleasant, and will most likely leave you feeling quite smart afterward.
In order to shorten links with this API, you will need an API key. This key will allow all shortened links to be automatically associated with the key’s account. One is automatically generated for you after registering a new account. No cost necessary. You will find this information listed under the “Accounts” tab of the Bit.ly dashboard once logged in. I will not be using a valid API key for this tutorial, so be sure to substitute your own in accordingly.
Automatic Shortening
David Walsh wrote up a nice PHP option for shortening links last Spring. It’s not the only way to access the API (e.g. JavaScript), but this method keeps account information private because the key is only visible server-side. His tutorial will be the basis for our Bit.ly integration.
Create a new PHP file for the shortening script. Mine will be called “shorten.php” for this tutorial. You will need to put in your own Bit.ly API information where noted in the script.
<?php
/*
Based on code from David Walsh
http://davidwalsh.name/bitly-php
*/
//Assign URL of page to shorten.
//Substitute with the_permalink() if using WordPress.
$full_url = "YOUR URL HERE";
/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
/* usage (replace with your account information) */
$short = make_bitly_url($full_url,'ENTER BITLY LOGIN','ENTER BITLY API KEY','json');
//Our short url is now stored in $short
?>I’ve copied a slightly modified code below for simplicity sake, but please refer back to his article for any further explanations or credit. The only difference is that the original echo statement is removed upon successful shortening. After running this script, we end up with a shortened version of the original URL stored in the $short variable.
The Page Setup
Create a new PHP file and paste in the code below. Notice that we are loading in the shorten.php script created in the last step at the top of the page. This area is also responsible for specifying the page title.
<?php //Calls Bit.ly shortener on current URL, returns $short variable with results REQUIRE_ONCE 'shorten.php'; //Assign title of page. Substitute with the_title() if using WordPress. $current_title = "Sample Page Title"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Share Feedback with Twitter and the Bit.ly API </title> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script type="text/javascript"> //jQuery code will go here </script> </head> <body> <h1>Share on Twitter</h1> <p>Select a response and post to your Twitter feed.</p> <p>I <select id="feedback"> <option value="Liked">liked</option> <option value="Interesting">was interested by</option> <option value="Inspired by">was inspired by</option> <option value="Absolutely loved">absolutely loved</option> <option value="Didn't like">didn't like</option> <option value="Completely disagree">completely disagreed with</option> </select> this post.</p> <p id="tweetit"><a href="http://twitter.com/home?status=Liked" target="_blank" title="Share link and feedback on Twitter">Tweet It</a><p> </body> </html>
Composing the Tweet with jQuery
jQuery will be responsible for taking all of the pieces and putting them into a functional link. Passing the $short variable from PHP to jQuery is surprisingly simple thanks to a well-placed echo statement. The code below should be added into the script tag created in the previous step.
<script type="text/javascript">
$(document).ready(function(){
//Assign initial values
var short_url = "<?php echo $short;?>";
var post_title = "<?php echo $current_title;?>";
var user_feedback;
var tweet;
function getFeedback(){
//Assign selected item to feedback
user_feedback = $("#feedback").val();
}
function composeTweet(){
//Compose the tweet
tweet = user_feedback + ': ' + post_title + ' ' + short_url;
//Update destination before sending tweet
$('#tweetit a').attr("href", "http://twitter.com/home?status=" + tweet);
}
$("#tweetit a").click(function(){
composeTweet();
});
//Update feedback when option is changed
$("#feedback").change(getFeedback);
//Get the initial feedback value from dropdown menu
getFeedback();
//Compose a default tweet
composeTweet();
});
</script>There’s a few main things to be aware of in the script above. The variables for short_url and post_title are assigned based on the contents of the PHP counterparts. The user_feedback variable will contain the “feedback” value (e.g. Love it) and the tweet variable contains the compiled result for Twitter.
There are two functions in charge of everything. The getFeedback function is responsible for updating the feedback value when the page initially loads and when the select box is changed. The composeTweet function combines the contents of all variables into a single tweet. Once the tweet is composed, the relevant “Tweet This” link (in next section) gets updated accordingly.
Simple Posting with Twitter

This is the easy part. Using a constructed URL, we’ll open Twitter in new window with the status box automatically filled. The user will need to submit the tweet template from Twitter before it is posted. Since we’ve already written the jQuery code responsible for setting the URL, the only thing left to do is create the target “Tweet This” link.
Make sure this link is in your final page result:
<p id="tweetit"><a href="http://twitter.com/home?status=Liked" target="_blank" title="Share link and feedback on Twitter">Tweet It</a><p>
Keep in mind that once the page is loaded, the jQuery script will overwrite the default link destination with the compiled tweet. I’ve set the target page to open in a new window for simplicity sake.
What about the API?
If you haven’t already been introduced to it, the Twitter API is wonderful. We won’t be using it for this tutorial, but I highly recommend spending a spare hour or two exploring options when you get the chance.
The API can do more than just fill in the status box, but requires a few extra steps. If you are interested in creating automatic tweets, you will need to have the user authenticate your site to their Twitter account. This would give you the ability to post to user’s accounts without having to open a new window for Twitter. If your site relies heavily on social media sharing, this might be the best option to explore. Depending on the response to this tutorial, an introduction to the API will probably find its way into an upcoming post.
Going Further
Depending on how long your post titles are, it might be a good idea to include a hashtag to identify your site. Implementing this would be as simple as adding another variable to the link construction in jQuery. If you got lost at any step of the way, I recommend downloading the project source files below to see the results in action. Remember that you will need to insert your Bit.ly account information before running the page successfully.
WordPress Integration
There’s also a fair amount of blog integration that can happen with WordPress template tags. I’ve commented in a few places where it might make sense to insert WordPress defaults. With a little luck and planning, you’ll be able to automate a similar system into your next theme update.
Have I missed anything? Thought of any cool applications for a feedback system like this? Be sure to share any comments or questions below.
Similar Posts
- How to Add Retweet Text with Tinyurl in WordPress Posts
- How to Add Twitter @anywhere in WordPress
- Automatically Shorten URL on Page Load in WordPress
- Visually Connect Elements on Web Page like Yahoo! Pipes
- Most Wanted Twitter Hacks and Plugins for WordPress

