A simple twitter feed block in Drupal 7 with Aggregator and Views, and nothing else!

🕔

Displaying a twitter feed on a website is easy as pie. Especially when you're using one of the top 5 CMS out there, chances are someone has already sorted it out for you and made it a module easy to plug in. It's the case with Drupal.

But there is another way for doing this if you want to have some fun with the Aggregator module -- provided by Drupal 7 core -- and Views, and only those.

This post was mostly inspired by this post from Scott Hadfield's blog, which was implementing a similar approach using the Customfield module, which I haven't managed to make work properly for some reason. So I've decided it would make a good excuse to grok Drupal theming some more.

I'm going to show you how to create a simple block that displays a twitter feed (or an aggregation of twitter feeds) using views and the aggregator module, and nothing more!

Setting up the twitter feed with Aggregator module

Before starting, make sure you have the Aggregator module enabled. If you're not sure how to do this, have a look at this little tutorial from siteground.com.

  1. Once this done, go to Home » Administration » Configuration » Web services » Feed aggregator,
  2. Create a new category and call it twitter feed, give it a title and a description, then hit save.
  3. Create a new feed and give it a title. We need also to give it the URL of you twitter feed, which should look like this
    https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=<username>
    Of course, replace <username> by you twitter username -- if you want to display you twitter feed.
  4. Before you save, put the feed into a category, the one we created earlier.

You can create as much feeds as you want and sort them into different categories. We'll use theses categories to build the views block.

Setting up the View

  1. Go to Home » Administration » Structure » Views and create a new view, Call it twitter_feed (or whatever, but if you decide to go with another name, know that we'll need again this name later with the customizations).
  2. It the Show drop down field, select Aggregator items, and leave them unsorted.
  3. Untick Create a page and choose Create a block of unformatted list, then hit Continue & edit;

Now we are going to select the information that we want to be displayed in the feed. In this example, I only want to display the tweet itself and the time it was tweeted.

So we will be picking two fields:

  • Aggregator: Body
  • Aggregator: Timestamp

Adding the Aggregator:body field

  1. In the fields section, click on add, then look for Aggregator:body in the long list of field you have.
  2. Untick Create a label, and save immediately

You can notice the body field doesn't exactly look like what we want: #hashtags and @usernames are not hyperlinked and they all start with you twitter name. Don't worry too much about it though, we'll fix it later.

Adding the Aggregator:timestamp field

  1. click on Add, look for Aggregator:timestamp
  2. Untick Create a label, choose a date format. There are plenty of them but if none suit you, you can make up a custom one. You might need to dig a bit into php's date formating for that. Hit save.

Customizing the output

Here is an example of what we have at the moment

TKrugg: gist.io: writing for hackers. for everything that doesn't fit into 140 characters. http://t.co/b0K6A7lu2T 2 hours 39 min ago

It's not quite there. We probably want 3 things: - get rid of the username TKrugg: at the beginning - convert URLSs to hyperlinks - make #hashtags and @usernames hyperlinks

This consists mainly in changing the value of the Aggregator:body field. This can be done by overriding the theme_views_view_field() function. This function in the one that outputs the fields of your views, whatever view or field it is.

We are going to override that function with another one slightly different. It will be basically the same, but we'll its behaviour so that in the case of our twitter_feed, it outputs the fields the way we want. The Drupal way of doing this is:

  • name that function yourtheme_views_view_field, replacing yourtheme by the name of yours
  • put it in the template.php file of your theme.

For the sake of this tutorial, let's assume your theme is called ymdot. No, it's not a silly name. That makes our function's name: ymdot_views_view_field.

You can get the code to start with here.


function ymdot_views_view_field($vars) {  
  return $vars['output'];  
}  

At first, the code of this function contains...well, nothing. That's how hooks should look like. But we're going to take care of it in a moment. The idea is simple, parse and change the string inside $vars['output'] to make it looks like a real tweet. So let's start by writing a function that'll do that. Brace yourself, you better brave with regular expressions ;)


function parseTweet($str) {
  
  // getting rid of the your username
  $user_pattern = '/^TKrugg: /'; 
  preg_match_all($user_pattern, $str, $users);
  foreach($users[0] as &$user){
    $str = str_replace($user, "", $str);
  }

  // taking care of urls
  $url_pattern ='/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
  preg_match_all($url_pattern, $str, $urls);
  foreach($urls[0] as &$url){
    $new_url = ''.$url.'';
    $str = str_replace($url, $new_url, $str);
  }

  // #hashtags
  preg_match_all('/#\w+/',$str, $hashtags);
  foreach($hashtags[0] as &$hashtag){
    $new_hashtag = ''.$hashtag.'';
    $str = str_replace($hashtag, $new_hashtag, $str);
  }

  // @usernames
  preg_match_all('/@\w+/',$str, $usernames);
  foreach($usernames[0] as &$username){
    $new_username = ''.$username.'';
    $str = str_replace($username, $new_username, $str);
  }

  return $str;
}

Even though this function might look long, what it does is very simple. First it removes the user TKrugg: thingy, then converts urls, #hashtags and @usernames to clickable anchors.

Now we're ready to write the new ymdot_views_view_field.


function ymdot_views_view_field($vars) {

  $view = $vars['view'];

  switch($view->name){
    case "twitter_feed":        // formatting of the twitter feed
      $vars['output'] = parseTweet($vars['output']);
      break;
    default:                    // all other views
      break;
  }

  return $vars['output'];
}

There you go! Your twitter feed should look like the one you're looking at on the right side of your screen at the moment (okay, maybe not now that you've scrolled all the way down).

There is probably much more work to do on a twitter feed, but this is an open door for all kinds of customizations, as long as the data provides by the twitter API allows it. Please feel free to share your experience and your opinion about my very first tutorial (yup !:)