How to: add a twitter dialog box anywhere on your blog

in Tutorials

Update: Twitter Anywhere is now deprecated. You won’t be able to use the method described below to insert a Twitter dialog box in your posts. Please check Twitter’s announcement post for alternatives.

Twitter has become a very useful tool for all bloggers, and allows us to share and promote useful articles to fellow bloggers. Naturally, we have seen more and more twitter functions integrated into our blogs; the latest Official twitter button has even made it easier to integrate twitter buttons on your blog.

But what if you do not want of a standard twitter button, but rather of a new and easy way for your readers to contact you via twitter? Luckily, Twitter @anywhere is here for you, and in that tutorial, we will see how to easily integrate at twitter box to any part of your blog, thanks to this service and the WordPress shortcodes! This can be done in a few easy step, and the result will look as below:

[twitterbox]

You will be able to customize the width and height of the form, as well as the message appearing by default in the box. Of course, as we will integrate this box with a shortcode, you will be able to integrate this tweetbox everywhere on your WordPress blog.

Here are the few steps to follow:

Create a new Twitter @Anywhere app

Go to http://dev.twitter.com/anywhere/apps/new, and create a new app with Read and Write access. The callback URL should be address of your blog.

Integrate the twitter API code in the header of your theme

In your theme’s  functions.php, integrate the call the twitter thanks to wp_enqueue_script, and then integrate the necessary script to integrate a twitter box into the head:

$api_key = "Add your twitter app API key here";
wp_enqueue_script("twitter-anywhere",
	"https://platform.twitter.com/anywhere.js?id={$api_key}&v=1");
add_action("wp_head", "twitter_box");

function twitter_box()
{
	echo '<script type="text/javascript">';
	echo 'twttr.anywhere(function (T) {T("#tbox").tweetBox({height: 100,width: 400,defaultContent: "<YOUR DEFAULT TWEETBOX CONTENT HERE>"});});';
	echo '</script>';
}

Thus you do not have to modify and clutter header.php with new lines of code, you can do it all through your functions.php file.

Create the shortcode

Again in functions.php, add the following lines:

function twitterbox_shortcode () {
	return '<div id="tbox"></div>';
}
add_shortcode("twitterbox", "twitterbox_shortcode");

And you’re done ! You can now use the shortcode [ twitterbox ] everywhere in your post content, in your theme widgets, and thus display a twitter box for your readers to contact you very easily via Twitter !

Any questions, or remarks? Do not hesitate to comment!

And of course, you can follow me on twitter too!