Skip to content

How to Integrate Twitters @Anywhere with your WordPress Comments

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:

  1. Add a Twitter username input box to your comment form
  2. Add a Twitter username box to registered user profiles (so logged in users don’t have to do anything)
  3. Save the Twitter username details using WordPress comment_meta functionality
  4. Display the Twitter username
  5. 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.

Share

Join me, Matt, Marko Randjelovic, redwall_hp. They're all chatting about "How to Integrate Twitters @Anywhere with your WordPress Comments" below ›

Read Comments

38 Comments »

  1. 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. :)

    • 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 :)

      • “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. :)

  2. 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!

    • 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(

  3. I’m confused by step #4. I assume you add a callback to comments.php so it looks something like this: ; then the code from #4 drops the opening/closing php tags and is placed in your functions.php file?

    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!

    • 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.

      • 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.

    • 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.

  4. 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!

  5. 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

    • 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.

  6. 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 :)

  7. 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?

Comments are closed. Let's continue the conversation on Twitter.
css.php