Ben
Ben is a lifelong Nintendo fan who likes to build websites, and make video games. He buys way too much Lego.
WordPress and Games
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.
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:
Before you start make sure you sign up for a Twitter API key for your website.
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>
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.
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); ?>
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'); ?>
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 } ?>
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.
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!
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. π
Wonderful Idea… I will try it…
I knew there was a way to do this without a plugin! Alright.
I always prefer using plug-in which do not require file updation. File edition leads to error when we change theme.
Thanks
Rajneesh
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!
Very useful information, as i try to minimize the number of plugins this will come in handy. Thanks !
Thanks Theo – glad you found it useful! π
I really do like this .. I will try to put it into my site..
A+++
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(
Very nice. Your tutorial is implemented in some blogs I visited :). Thanks for sharing to us.
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.
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!
Just a little update: the hover cards are suddenly appearing in Opera. Twitter must’ve changed something…
Nice one – thanks for the heads up.
Sure thing. Thanks again for the great article. π
Thank you for your good plugin!
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.
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 π
VERY, VERY nice. I just implemented this on my wife’s blog (http://bookalicio.us/) in just 10 minutes. Thanks a lot!
Hey Marco – great to see it being used.
Hey!! Thnks!! Great post, but Can you help me?? I want to make a comment section like this website (http://mexico.cnn.com/entretenimiento/2010/11/23/el-disco-que-lennon-firmo-a-su-asesino-antes-de-morir-sale-a-la-venta) Is possible with wordpress?
That’s a bit more advanced than WordPress does at the moment I am afraid.
Hahaha XD At the moment I will use @anywere just as you indicate in your post. THnks!!
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?
Awesome tutorial, but I’m a little confused on #4. Could you clarify a little more what to do there?
What part of that confuses you? I don’t know how to explain it more simply
I guess location…functions.php?
you guess right π