Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196
News

Integrate Twitter into WordPress

EVER THOUGHT IT WOULD BE COOL TO STREAM YOUR TWEETS INTO YOUR WORDPRESS TEMPLATE? WE SHOW HOW IT CAN BE ACHIEVED

TWITTER IS A microblogging platform that allows you to post messages up to 160 characters long, updating ‘followers’ with your news, current activity or status. Many web users have embraced the idea of Tweeting as a complementary platform to the normal blog, allowing them to reach out to other Twitter users and fill the gap between something worthy of a full blog post and something incidental. The platform is rapidly growing in popularity; Stephen Fry has just reached 20,000 followers within a month or so of joining Twitter, and even Web Designer has its own Twitter account – our username is WebDesignerMag. Sign up for Twitter at http://twitter.com.
So, microblogging is a useful and fun way of sharing news, but what about your existing blog readers? They may not be aware that you’re using Twitter and may not use Twitter themselves. This is no reason to exclude them from your Twitter updates, however, and in this tutorial we’re going to take advantage of the Twitter JSON search API by using jQuery to insert a live view of your latest Tweets directly into your blog pages.

01 Keep it simple to begin with

We’ll be inserting our final code into a WordPress blog sidebar, but to start with we’ll test with an otherwise empty HTML file to ensure everything works as it should do. Copy the start.html’ and ‘jquery-1.2.6.pack.js’ files from the disc onto your computer. Open the HTML file up in your favourite browser and your HTML editor of choice – in this instance Dreamweaver CS3 or CS4.

02 API documentation
step02

We’re using JSON because it allows us to load content cross-domain – that is, we can grab content from another server without coming up against the problems associated with trying
to load XML from an external server using JavaScript. Twitter offers a JSON feed as part of the search API. You can read the specifications at http://apiwiki.twitter.com/Search+API+Documentation. Try entering http://search.twitter.com/search.json?q=from%3Awebdesignermag&rpp=5&callback=? into your browser and save the file that the browser offers you as a download. Open the file up in a text editor, such as Notepad or TextEdit, and familiarise yourself with the contents. This loads the five latest Web Designer Twitter posts.

03 Set up the jQuery

Now we understand what’s going on with the feed, we can get started with our JavaScript. At the top of your blank HTML document, enter the code below within the <head> section. This loads the jQuery script into the page and sets up a script to be run when the document has finished loading into the browser (note that this is different to the regular JavaScript onLoad event as it doesn’t require all the images to have loaded before running – a bonus for script performance).

<script type=”text/javascript” src=”scripts/jquery-1.2.6.pack.js”></script>
 <script type=”text/javascript”>
 $(document).ready(function(){
 (Our scripting will go in here.)
 });
 </script>

For the purposes of testing our design layout for the Twitter panel, add the following immediately beneath the script code:

<style>
 body {
 font-family: arial, helv, sans-serif;
 font-size: 66%;

04 Grab the JSON feed

We’re going to use jQuery’s built-in getJSON function to grab the feed dynamically. This function loads the feed from the address we parse in, and automatically instantiates the
objects contained within it. The JavaScript equivalent would be to use the eval() function on the text that’s loaded, but jQuery deals with this for us so we don’t need to worry about it. Add the code below inside the $(document).ready function:

var url = “http://search.twitter.com/search.json?q=from%3Awebdesignermag&rpp
 =5&callback=?”;
 $.getJSON(url, function(data){
 // When the data is loaded, this script will run
 });

05 Set up a loop

The code we’ve added so far doesn’t display any sign that it’s done anything, but all the data has, in fact, been loaded into your page. Now we need to get the data to print out into our page. It’s important to understand that we’ve created an object by loading the JSON feed. This object is called ‘results’ in this particular case, and it contains an array of items. Each item inside the results object has several properties supplied by the Twitter API. These properties range from the text of the Tweet itself through to the time it was posted, who posted it, who (if anyone) the Tweet was directed at and so on. With this in mind, we need to set up a loop to iterate through the results object, picking up each item in turn and extracting some of these properties, printing them out to screen. In JavaScript, we would achieve this with a for loop, but jQuery gives us the .each function, which makes the code a lot easier to read and understand. Add the followingcode inside the $.getJSON callback function:

$.each(data.results, function(i,item){
 alert(item.text);
 });

06 Test in your editor or browser
step06

We’ve got far enough now to test our page so far. Save your document and open it in a browser, or if you’re using an editor such as Dreamweaver CS4, which has a live preview of your code, you can test within your editor. Either way, you should now see a series of five alert boxes when you open your page. Each alert box will contain a Tweet from the feed.

The results are limited to five in number because of the URL parameters we parsed in to Twitter’s API. See the &rpp=5 in the URL we used? Try changing the five to ten and testing the page again. When you’re done, remove the alert statement, as we’re going to put in our final code in a moment.

07 Consider the design approach
step07

How you choose to display each Tweet will vary according to the rest of your blog design. Here, we’re using the standard theme that ships with WordPress, so there’s quite a lot of scope for how we style the content. If your theme doesn’t suit the style we’re going to be using, adapt the design approach to match your own blog. We’re going to use a small number of fields in our design: the text of the Tweet, the name of the user who posted the message, the date it was posted and finally, the user’s avatar image. We’ll float our image left and align the text elements to the right of the avatar for a simple, straightforward look.

08 Append your content
step08

We’re going to want to specify where our content is inserted, so start off by adding a div tag with an ID of ‘tweetscontainer’ into your page body section.

<div id=”tweetscontainer”></div>

Now we have our container, we’ll append our output inside this. First, we need to grab it inside our script. Insert the code below underneath the line that reads var url=”http://
search.twitter…..”:

var tweets = $(‘<ul id=”tweets”>’).appendTo(“#tweetscontainer”);

This code creates an unordered list, creates a reference to it of ‘tweets’ and appends it inside the tweetscontainer div we just made. Next, we’ll add a list item for each result item and append it to the <ul>. Add the code below where we previously had the alert() code:

tweets.append(‘<li>’+item.created_at+’: ‘+item.text+’</li>’);

Save and test your page again. You should now see an unordered list with each item
containing a date/time and Tweet text.

09 Add the missing bits

We’ll add the remaining text element we wanted to include; the name of the user posting – in this case the username will always be ‘WebDesignerMag’, but you’ll see later that this same code will work for any Twitter search query. Change your tweets.append line to read as below:

tweets.append(‘<li><p><a href=”http://twitter.com/’+item.from_user+’/statuses/
 ’+item.id+’” title=”Click here to view this on twitter”>’+item.from_user+’</a> at
 ‘+item.created_at+’: ‘+item.text+’</p></li>’);

You’ll notice that we’ve added a link to the specific Tweet page on Twitter as well as the name of the Tweeting user. You can construct any HTML you desire simply by adding it in the same way.

10 Add some style

Now that we’ve got some Tweets appearing with all the text we need, let’s give it some styling. We’re going to use a fairly straightforward approach. Style the text in the same font as the rest of the page, at 1em, and the links in bold. Add the following style rules within your <style> section:

#tweets {
 width: 300px;
 margin: 0;
 padding: 0;
 font-size: 1em;
 }
 #tweets li {
 margin: 0;
 padding: 0;
 list-style: none;
 clear: left;
 }
 #tweets img {
 float: left;
 margin: 0px 10px 10px 0px;
 }
 #tweets li p {
 margin-left: 83px;
 }
 #tweets li a {
 font-weight: bold;
 text-decoration: none;
 }
 #tweets li a:hover {
 text-decoration: underline;
 }

11 Save and test
step11

Save your page again and open it up in your browser to run another test. You’ll see that our content looks a lot closer to our aim now. We’re missing our avatar images, which we’ll insert next, but notice also that if there are any URLs in the Tweets, they aren’t hot – that is, they aren’t turned into links automatically. We’ll deal with this issue once we’ve got the
avatar image in place.

12 Add avatar images

The content looks good, but as we’ve just established, we’re missing the avatar images. These are hosted by Twitter, and you can access the image URL directly from the JSON feed using the property profile_image_url. Add the code below in-between the <li> and <a> within your tweets.append statement:

<img src=”’ + item.profile_image_url +’” alt=”’ + item.from_user +‘” width=”73” height=”73” />

Then add the CSS rules below to your style sheet area to float the image to the left of your Tweet content:

#tweets img {
 float: left;
 margin: 0px 10px 10px 0px;
 }

13 Make URLs hot

The final thing we need to do is to make those URLs hot. We’ll use regular expressions to do this. There’s not enough
space to explain the finer points of these here, but if you’re unfamiliar with regular expressions, search Wikipedia,
Google or W3Schools for more info. Find the part of the tweets.append code that reads item.text+’</p></li>’; and
replace it the code below. Note that we search for all URLs in the Tweet text, and also instances of @

[text][/text]

. The latter is how Twitter users alert each other to their messages; the @ symbol precedes a Twitter username. We’ll make the @

[text][/text]

instances point to the specified user’s Twitter page, and the URLs point to where they look like they point:

item.text.replace(/(w+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&?/.=]+)/gi, ‘<a href=”$1”>$1</a>’).replace(/[@]+([AZa-
 z0-9-_]+)/gi, ‘<a href=”http://twitter.com/$1”>@$1</a>’)+’</p></li>’);

14 Test cross-browser

Your blog now features your most recent five Tweets in the sidebar. Congratulations! A word of caution, however; as with any JavaScript coding and CSS styling, you should ensure you’ve tested across all the major browsers for compatibility and bugs. Thankfully, jQuery deals with a lot of the cross-browser differences in scripting, but don’t forget to check your CSS in as many browsers as possible to ensure everything displays as expected.

15 Put it into your blog
step15

We’ve got all the functionality tested and styled up, so let’s get it into our blog. This process will vary from platform to platform, but here we’re using the ever-popular WordPress v2.6. From the admin dashboard menu, choose Design>Widgets and add a new text widget. Edit the text widget and paste your Tweet’s HTML div tag into the widget. Choose Theme Editor and paste your CSS into the main style sheet for the theme you’re using (we’ve got the default K2 theme installed here). Finally, choose the theme header.php file and paste in your JavaScript code within the <head> section of this file. Save all your changes and preview your blog.

16 Other JSON feeds
Now you’ve mastered using JSON feeds, extracting and displaying the data, styling and dynamically creating links, have a look at some of the other social websites you may use. Flickr, for example, offers a JSON feed for photos tagged with particular keywords, users and groups. You can also use the Twitter API to search for keywords or messages directed at specific users rather than posted by specific users. Try changing your JSON URL to http://search.twitter.com/search.json?q=StephenFry&rpp=5&callback=? to see messages directed towards Stephen Fry. Use JSON feeds from your favourite social websites and display their content directly on your blog.

(This article was originally written by Sam Hampton-Smith, published in issue 153)

×