Darren Mothersele

Software Developer

Warning: You are viewing old, legacy content. Kept for posterity. Information is out of date. Code samples probably don't work. My opinions have probably changed. Browse at your own risk.

Simple Twitter Block for Drupal

Jan 15, 2009

web-dev

Here's a quick way to add recent tweets to your Drupal powered websites. The following code is as simple as possible. Add it to your site's module folder and enable the module. You they get a block to position on your site. The block is populated with your most recent tweets via a Javascript call to the Twitter website.

First thing to do is create the module info file so Drupal can find your module. I'm going to call the module tweetblock - but you can change this if you like. I put the following code in a file called "tweetblock.info"

name = Twitter Block
core = 6.x
package = Other

Then I create the main module in a file called "tweetblock.module" with the following code:

<?php
function tweetblock_block($op = 'list', $delta = 0, $edit = array()) {
  if (
$op == 'list') {
   
$blocks[0] = array(
     
'info' => t('Twitter'),
    );
    return
$blocks;
  }
  if (
$op == 'configure' && $delta == 0) {
   
$form['tweetblock_username'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Twitter Username'),
     
'#default_value' => variable_get('tweetblock_username', 'mothersele'),
    );
   
$form['tweetblock_count'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Number of items'),
     
'#default_value' => variable_get('tweetblock_count', 6),
    );
    return
$form;
  }
  if (
$op == 'save' && $delta == 0) {
   
variable_set('tweetblock_username', $edit['tweetblock_username']);
   
variable_set('tweetblock_count', $edit['tweetblock_count']);
  }
  if (
$op == 'view' && $delta == 0) {
   
$tweetcode = "";
   
drupal_add_js($tweetcode,'inline','footer');
   
$block = array(
     
'subject' => t('Twitter'),
     
'content' => "<div id="twitter_div"><ul id="twitter_update_list"><li>...loading...</li></ul></div>",
    );
    return
$block;
  }
}


function
tweetblock_footer($main = 0) {
 
$username = variable_get('tweetblock_username', 'mothersele');
 
$count = variable_get('tweetblock_count', 6);
  return
"<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script><script type="text/javascript" src="http://twitter.com/statuses/user_timeline/{$username}.json?callback=twitterCallback2&amp;count={$count}"></script>";
}
?>

That's just two functions. The first defines a Drupal block called "Twitter" which will contain your recent twitter updates. It defines two new block settings, one for your twitter username, the other for the number of tweets to show.

The second function adds the Javascript call to the footer of your page. This means your page loads completely before the tweets are fetched. The javascript call requests your recent tweets from the twitter server and adds them to the block created by the first function.