We’ve all seen this before when commenting on a blog post we’ve just read. The standard comment form on a WordPress-driven website asks for a user’s name, email address (not published), website address and their comment. What if we could get some other information from the user*, and later integrate that into their comment? Why not get their Twitter username and link back to their Twitter profile as well as to their website? This tutorial will explain how to do just that.
* While this tutorial uses a Twitter username as an example, virtually any additional information supplied by the user can be stored along with their comment (a rating, a selection of their social media profiles, etc).
Asking for it by name (aka. creating the Twitter username textfield)
Here we’ll add a field to the comment form, in which the user can input their Twitter username. The snippet of code I’ve used for this is as follows:
<p><label for="twitter">Twitter</label><input type="text" name="twitter" id="twitter" value="" /></p>
The above code adds a field to the comment form of the theme in question. I’d recommend making a copy of the way the website field is generated and replacing all instances of the word “website” with the word “twitter”. This is an easy way to ensure consistency with the theme to which you are adding this functionality.
Okay, lets store this thing!
Right. The user has entered their Twitter username. Lets store it along with the comment, using the comment meta functionality provided by WordPress.
What we’ll be doing here is the following:
- Check if the user inputted a Twitter username.
- Sanitize the username.
- If there are any characters left after we’ve sanitised the username (it removes all unwanted characters), store the Twitter username along with the comment.
And here’s how that looks in code:
<?php/*** Storing the commenter's Twitter username.*/function matty_store_twitter_username ( $post_id ) {$twitter_username = $_POST['twitter'];if ( $twitter_username ) {$twitter_username = sanitize_user( $twitter_username, true );$twitter_username = str_replace( ' ', '', $twitter_username );$twitter_username = str_replace( '.', '', $twitter_username );} // End IF Statementif ( $twitter_username ) {add_comment_meta( $post_id, 'twitter', $twitter_username, true );} // End IF Statement} // End matty_store_twitter_username()add_action( 'comment_post', 'matty_store_twitter_username', 1 );?>
Pretty simple, right?
If you make use of the above or know of other ways of achieving this, please share your thoughts in the comments below.
In a follow-up tutorial, I’ll discuss how to integrate this stored Twitter username into comments on your WordPress website, using a custom comment callback function.
2010-05-03: Code updated thank to feedback from Ben in the comments below. Thanks man. π
Leave a Reply to SoWhat Cancel reply