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 on WordPress

My Twitter @Anywhere Hovercard on WordPress

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.

Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).

Link to this page

Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.

WordPress News

The latest WordPress updates from the WPBriefs Podcast.

Related Posts

27 May 2013

WordPress: 10 Years Young, What Does The Future Hold?

WordPress is now 10 years old. I started using wordpress 9 years ago – which means I joined the WordPress community early on. The reason I chose WordPress is simply because of the fabled 5 minute install process – I...
12 Apr 2013

My First Website

My first website was terrible. Not intentionally I hasten to add – but because I was told to make it bad…I started university in 1998, the internet was just starting to become more mainstream. It was still a few years...