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

Share Feedback with Twitter

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:

  1. Reading: Article Name / Article Link
  2. I absolutely loved: Article Name / Article Link
  3. Made me think: Article Name / Article Link
  4. Completely disagree: Article Name / Article Link
  5. 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 Dashboard

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

A sample tweet
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.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Zach Dunn

Zach is a partner and interface designer at One Mighty Roar from Massachusetts, USA. Follow him on Twitter @zachdunn.

 

Discussion

  1. Design Informer

    February 19th, 2010 at 12:37 PM

    WOW! This is awesome Zach. Really something that I need to look into. Keep up the great work. You guys are always coming up with these excellent tutorials.

  2. Armin C.

    February 19th, 2010 at 1:26 PM

    I like it. My inputs:
    1. In the demo, I think you made the background of the options red by accident?
    2. How about adding a option for a totally custom input?
    That way users can still save time with premade comments and if they want even more personalisation they can input their own comment, quicker than usual.

    All in all a very nice tutorial :)

  3. Codesquid

    February 19th, 2010 at 2:54 PM

    This is a neat idea! A really simple little trick to help user give more meaningful feedback!

  4. Michal Kozak

    February 19th, 2010 at 7:33 PM

    Nice idea. Kinda strange nobody thought of that this way before.

  5. Bart

    February 20th, 2010 at 10:41 AM

    Well this seems to be a good solution but i have noticed that many providers don’t allow to read files from different servers as the request comes from.

    so instead of file_get_contents(); i recommend to use the curl functions for getting the response from the bit.ly API..

    here is my solution:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bitly);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $response = curl_exec($ch);
    curl_close($ch);

    just replace line 21 in the make_bitly_url function with this code to make it work.

  6. Kawsar Ali

    February 20th, 2010 at 3:19 PM

    Sweet nice one. Should be useful

    Also, you guys might want to include the article title and wordpress short url for the tweet button at the bottom of each post . Right now it just says “Currently reading”.

  7. Johnny

    February 21st, 2010 at 3:12 PM

    Really good post, it’s nice to get an insight into how these sort of things work. :)

  8. Martin Leblanc

    February 21st, 2010 at 3:19 PM

    This is a fantastic idea.

  9. mahmoud kamal

    February 22nd, 2010 at 6:29 AM

    good idea Zach Dunn ;)

  10. liam

    February 22nd, 2010 at 12:06 PM

    This is a really useful idea and well pulled off. Very nice.

  11. Monica

    February 22nd, 2010 at 6:20 PM

    thanks for the tutorial. the bitly api is really user-friendly, i just never thought of using it in this way.

  12. Jordan Walker

    February 23rd, 2010 at 9:45 AM

    That is a really neat tool that can be directly implemented. Great work!

  13. Amberly | Web Designer

    February 23rd, 2010 at 10:45 AM

    This is awesome.. thanks for sharing..

  14. çiçekçi

    February 23rd, 2010 at 12:30 PM

    hi

    This is a really useful idea and well pulled off.
    thanks

  15. Smashing Share

    February 26th, 2010 at 12:32 AM

    very nice one. i like it

  16. Josh

    March 6th, 2010 at 10:16 AM

    Thanks for putting this together Zach. Very nice and an inspiring change for the usual ones you see around. Especially with the select box options idea

  17. Ian Evans

    April 15th, 2010 at 2:11 AM

    We have the rare title that is over 140 characters…how does the script handle that? Thanks!

  18. Zach Dunn

    April 15th, 2010 at 8:06 AM

    @Ian

    The script doesn’t handle this currently. Tweets that are over 140 characters will not be transferred into Twitter. I recommend you throw in a character counter or have a short version ready for the tweet version. You could save it as post metadata.

  19. sigara bırakma merkezi

    May 12th, 2010 at 5:12 AM

    Really good selections. I like the Sunset Bees one, so warm and summery.

  20. John Media@dedicated server

    June 9th, 2010 at 7:04 AM

    Quite a nice tutorial I did learned a lot about using this in my WP site. I’m quite happy you’ve included in some codes and screenies thanks

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!