Last week Twitter released @Anywhere, a system for more easily integrating Twitters features into your website. I'm a bit of a fan of Twitter so decided I wanted to add it to Binary Moon, and on Saturday I released the first version.

My Twitter @Anywhere Hovercard in WordPress Comments
The first place I saw this functionality was on Webmaster Source, so I asked Matt if he would share his code with me - and very kindly he said yes. I then integrated the functionality into my WordPress theme, Elemental, refining the code - making it more sturdy and foolproof. Below is a tutorial showing what I did.
The code was split into a number of elements. You need to:
- Add a Twitter username input box to your comment form
- Add a Twitter username box to registered user profiles (so logged in users don't have to do anything)
- Save the Twitter username details using WordPress comment_meta functionality
- Display the Twitter username
- Add the JavaScript to insert the Twitter @Anywhere hovercards
Before you start make sure you sign up for a Twitter API key for your website.
1. Add a Twitter username input box to your comment form
Add the Twitter input box to your comment form. This will move around based upon the template you're using but generally it's somewhere inside comments.php. In addition you may need to change the format of the html so that it fits in the design of your comment form.
<p>
<input type="text" name="twitter_username" id="twitter_username" class="text" value="<?php echo bm_getCurrentTwitterUser(); ?>" size="22" tabindex="4" />
<label for="twitter_username"><?php _e('Twitter Username', BM_THEMENAME); ?></label>
</p>
1. (Part 2) Remember the Twitter username
The default value for the Twitter username above is actually stored in a cookie when the Twitter name is saved in point 3 later on. This is so that returning users don't have to re-enter their usernames over and over. It also keeps things consistent with the email address and website that WordPress already remembers for you. The function used in part 1 above should be added to your themes functions.php and looks like this:
function bm_getCurrentTwitterUser () {
$comment_twitterUser = '';
if (isset($_COOKIE['comment_twitteruser_' . COOKIEHASH])) {
$comment_twitterUser = $_COOKIE['comment_twitteruser_' . COOKIEHASH];
$comment_twitterUser = stripslashes ($comment_twitterUser);
$comment_twitterUser = esc_attr ($comment_twitterUser);
}
return $comment_twitterUser;
}
Note that there is some sanitisation done in this function to prevent possible cookie modification which could lead to security issues.
2. Add a Twitter username box to registered user profiles (so logged in users don't have to do anything)
Matt's original code suggested adding a custom options page but I was already saving all users Twitter details in their profile page using some code on extending user contact information that I learnt via WPEngineer. Very clean and simple, and it adds into a logical place. I am storing this so that registered users do not need to enter the details repeatedly, and also so that old comments by registered users get the Twitter hovercards added dynamically (without having to edit loads of comments).
<?php
function my_new_contactmethods( $contactmethods ) {
$contactmethods['twitter'] = 'Twitter';
return $contactmethods;
}
add_filter('user_contactmethods','my_new_contactmethods',10,1);
?>
3. Save the Twitter username details using WordPress comment_meta functionality
For non-loggedin users I want to save the Twitter username using the comment_meta functionality added in WP 2.9. The comment_meta functionality works in much the same way as the post_meta code does. Supply a comment id a variable name, and some values and WordPress does the rest. This code should be added to functions.php and makes use of the comment_post action.
<?php
function bm_saveTwitterUser ($post_id) {
global $user;
// only save the twitter details for users who are not logged in
if (!is_user_logged_in()) {
// if an account name is specified
if (isset($_POST['twitter_username'])) {
// save cooke for...
$comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
// sanitize username
$twitter_user = esc_html ($_POST['twitter_username']);
$twitter_user = str_replace('http://twitter.com/', '', $twitter_user);
// save cookie to use in comment form
setcookie('comment_twitteruser_' . COOKIEHASH, $twitter_user, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
// save name to db
add_comment_meta ($post_id, 'twitter_user', $twitter_user, true);
}
}
}
add_action ('comment_post', 'bm_saveTwitterUser');
?>
4. Display the Twitter username
This is split into a couple of parts. First check if the commenter is logged in, if so use their logged in Twitter username. If they're not logged in then try for a comment_meta username. Then display it all.
I added this into the comment callback function so that I can use nested comments. There's info on this on the WordPress Codex
<?php
$twittername = '';
$commentAuthorUrl = get_comment_author_url();
if ($comment->user_id > 0) {
$auth = get_userdata ($comment->user_id);
}
if (isset($auth->twitter)) {
$twittername = $auth->twitter;
} else {
$twitter_user_array = get_comment_meta (get_comment_ID(), 'twitter_user');
if ($twitter_user_array[0]) {
$twittername = $twitter_user_array[0];
}
}
if ($twittername != '') {
?>
(<a class="twitter_anywhere" href="http://twitter.com/<?php echo $twittername; ?>">@<?php echo $twittername; ?></a>)
<?php
}
?>
5. Add the JavaScript to insert the Twitter @Anywhere hovercards
The Twitter @anywhere JavaScript is the code that pulls everything together, adding the hovercards and making it easy for people to make friend requests. I added this code to footer.php, right before the '' tag so that any problems with Twitters service wouldn't stop the site from functioning.
<script src="http://platform.twitter.com/anywhere.js?id=YOUR_API_KEY&v=1"></script>
<script type="text/javascript">
twttr.anywhere(function(twitter) {
twitter('.commentlist').linkifyUsers();
twitter('.twitter_anywhere').hovercards({
infer: true
});
});
</script>
You will probably need to customize the JavaScript above so that Twitter replace the hovercards in the correct areas of the code.
Your Turn
There's quite a few bits of code above but it's actually quite easy to put the whole lot together. If you make use of it then let me know in the comments, I'd love to see what you do.
Hi,
Thanks for showing how to make use of comment meta data!
Now I know how it works.
Thanks!
May 6, 2010 • @@denzelchia
Nice write-up. I see you've made a few improvements to my code. I like the cookie idea, and I hadn't thought of checking to make sure nobody put the full URL instead of just the username. I'm going to have to update my site.
May 6, 2010 • @redwall_hp
Yeah - I changed a few little bits and pieces, but your code was a great help to get me on the right track, thanks again for sending it over.
My goal is always to make things as fool proof as possible, you never know what people will do
May 8, 2010
"My goal is always to make things as fool proof as possible, you never know what people will do"
At least WordPress takes care of the Bobby Tables issue through it's own sanitization.
May 8, 2010 • @redwall_hp
Wonderful Idea... I will try it...
May 8, 2010 • @jauhari
I knew there was a way to do this without a plugin! Alright.
May 8, 2010 • @loneplacebo
I always prefer using plug-in which do not require file updation. File edition leads to error when we change theme.
Thanks
Rajneesh
May 9, 2010 • @rajneeshsaini
Very clever, but I will stick with Intense Debate as it has a ton of options...
I can certainly see a 'lot' of people loving the feature described here though for those who don't want what I use instead
Great post Ben!
May 9, 2010 • @jameswoodcock
Very useful information, as i try to minimize the number of plugins this will come in handy. Thanks !
May 10, 2010 • @Theocb
Thanks Theo - glad you found it useful!
May 10, 2010
I really do like this .. I will try to put it into my site..
A+++
May 13, 2010 • @256studio
I think that facebooks fbml is much more seamless than what is possible with Twitters Anywhere but a great tutorial regardless. . . . too bad it isn't possible to have a mash up of the too =o(
July 19, 2010 • @crooksblogger
Very nice. Your tutorial is implemented in some blogs I visited
. Thanks for sharing to us.
May 13, 2010 • @rilwis
I'm confused by step #4. I assume you add a callback to
comments.phpso it looks something like this:; then the code from #4 drops the opening/closing php tags and is placed in yourfunctions.phpfile?If that's the case, wouldn't #4's code need to be wrapped in something like
function mytheme_comment() { ... }? I'd appreciate some more comments or clarification on this step for modifying the comment output.Thanks!
May 20, 2010 • @inlikealion
Oops, didn't think about the code blocks being block and not inline - previous post looks annoying with all the code sections around file names =[.
The "like this:" code block should contain the standard php wp_list_comments ( 'callback=mytheme_comment' ) without some of the spaces.
May 20, 2010 • @inlikealion
Hi Matt - you're right. Sorry if it wasn't clear. You need to stick this into the custom comment callback function so that the Twitter username can be displayed with the rest of the message.
May 20, 2010
Ok, I got it. I realized that #4's code is simply placed within your custom callback in functions.php. I've got it up and running now.
Thanks, Ben, for the tutorial.
May 20, 2010 • @inlikealion
This is really cool. I've implemented it into my website and it works just fine. Thanks for sharing!
There is a little quirk with the hovercards though: they won't appear in Opera. Have you any idea why that happens (or rather: doesn't happen)?
Thanks again!
May 23, 2010 • @iodicdesign
Just a little update: the hover cards are suddenly appearing in Opera. Twitter must've changed something...
May 30, 2010 • @iodicdesign
Nice one - thanks for the heads up.
May 30, 2010
Sure thing. Thanks again for the great article.
May 30, 2010 • @iodicdesign
Thank you for your good plugin!
May 29, 2010 • @cantonbolo
An easy way to integrate twitter comments into your wp comment area is by installing Disus, not coding necessary. I installed it in my blog, you can see how it works. blog.bluemediaconsulting.com
June 29, 2010 • @marysheaven
That's true, but to be honest I just don't like Discus. I find it really messy and would rather implement the code myself.
June 29, 2010
Hey Ben, great info!
One question though. I am trying to use the ajax function that the "WP Thread Comment" offers on comments, but when using ajax the comment doens't save the comment-metadata...Any ideia which direction to go?
Thank you
July 29, 2010
VERY, VERY nice. I just implemented this on my wife's blog (http://bookalicio.us/) in just 10 minutes. Thanks a lot!
July 31, 2010 • @TheMarco
Hey Marco - great to see it being used.
August 1, 2010
Hey!! Thnks!! Great post, but Can you help me?? I want to make a comment section like this website (http://mexico.cnn.com/...-antes-de-morir-sale-a-la-venta) Is possible with wordpress?
November 23, 2010 • @IgnacioCubillas
That's a bit more advanced than WordPress does at the moment I am afraid.
November 24, 2010
Hahaha XD At the moment I will use @anywere just as you indicate in your post. THnks!!
November 24, 2010 • @IgnacioCubillas
I want to do this at my site, but I am using the Thesis theme (1.8) and there is no way to add the first portion of code to the comments file.
Any suggestions?
February 13, 2011 • @jhsiess
Awesome tutorial, but I'm a little confused on #4. Could you clarify a little more what to do there?
April 8, 2011 • @xmusicispassion
What part of that confuses you? I don't know how to explain it more simply
April 21, 2011
I guess location...functions.php?
April 28, 2011 • @xmusicispassion
you guess right
April 30, 2011