16 Newest and Best Twitter Hacks for Your WordPress Website

As Twitter has quickly risen to become one of the most popular websites on the internet, is has become increasingly crucial that WordPress websites rise to the occasion and deeply integrate with the world's second-most popular social media website. There are plenty of ways to do this, both on the website itself and within the WordPress Dashboard.

The 16 Newest and Best Twitter Hacks for Your WordPress Website

With a robust combination of Twitter hacks and WordPress plug-ins, the world's most popular content management software can be easily integrated with Twitter in new, exciting, and highly useful ways.

Twitter Hacks for Your WordPress Website

1. Create a "Tweet This" Button to Be Displayed with Posts

One of the best ways to promote website content and encourage it to go viral is to allow readers to share each post via Twitter. This is done by placing a relatively basic line of code within the standard WordPress Loop, enabling users to create a tweet that automatically links to the post's permalink. Here's how it looks in most cases:

<a href="http://twitter.com/home?status=I think you should read <?php the_permalink(); ?>" title="Send to Twitter">Tweet About This Post!</a>

The code, when added into the WordPress Loop, will render alongside every post and allow for quick sharing of content. Best of all, it's XHTML valid and requires no special JavaScript to get the job done.

2. Display the Website's Total Number of Twitter Followers

In order to create an air of popularity, it might be a good idea to show how many people follow the blog's Twitter account. This method could also be used to show how many people follow a specific author's account, thereby encouraging new visitors to log on to Twitter and do the same. This involves a relatively long function within the theme-specific functions.php file, as well as a small piece of PHP code in any of the template files where followers should be displayed. The function looks like this example:

function string_getInsertedString($long_string,$short_string,$is_html=false){
    if($short_string>=strlen($long_string))return false;
    $insertion_length=strlen($long_string)-strlen($short_string);
    for($i=0;$i<strlen ($short_string);++$i){
    if($long_string[$i]!=$short_string[$i])break;
}
    $inserted_string=substr($long_string,$i,$insertion_length);
    if($is_html && $inserted_string[$insertion_length-1]=='<'){
       $inserted_string='<'.substr($inserted_string,0,$insertion_length-1);
    }
    return $inserted_string;
} 

function DOMElement_getOuterHTML($document,$element){
    $html=$document->saveHTML();
    $element->parentNode->removeChild($element);
    $html2=$document->saveHTML();
    return string_getInsertedString($html,$html2,true);
}

function getTwitterFollowers($username){
    $x = file_get_contents("http://twitter.com/".$username);
    $doc = new DomDocument;
    @$doc->loadHTML($x);
    $ele = $doc->getElementById('follower_count');
    $innerHTML=preg_replace('/^< [^>]*>(.*)< [^>]*>$/',"\\1",DOMElement_getOuterHTML($doc,$ele));
    return $innerHTML;
}

With this code placed into the theme-specific functions.php file, a username can be supplied by an external line of PHP code in order to return a specific account's followers. That's done by placing the following code into one or more of the current theme's template files:

We have <?php echo getTwitterFollowers("YourTwitterUserName")." followers on Twitter"; ?>.

3. Display the Latest Tweet on the WordPress Site

To display the latest tweet anywhere on the WordPress site, including the header, sidebar, footer, or even the main content area, a simple PHP snippet can be used. This code is entirely self-contained, and can be placed directly into a template file. Here's how it looks:

<?php
$username = "YourTwitterUsername"; // Put your username here.
$prefix = "My Latest Tweet"; // Any text that goes before the tweet itself.
$suffix = ""; // Any text that should be placed directly after the tweet.
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";

function parse_feed($feed) {
    $stepOne = explode("<content type=\"html\">", $feed);
    $stepTwo = explode("</content>", $stepOne[1]);
    $tweet = $stepTwo[0];
    $tweet = str_replace("&lt;", "<", $tweet);
    $tweet = str_replace("&gt;", ">", $tweet);
    return $tweet;
}

$twitterFeed = file_get_contents($feed);
    echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);
?>

The PHP snippet above uses the built-in RSS parsing engine that ships with WordPress. It uses the "username" variable to read an account's RSS feed, and posts the latest tweet in that feed to the website. The prefix and suffix areas allow the tweet to be placed into context, all within the self-contained PHP code.

4. Display the Latest Tweets from Multiple Authors

The code mentioned in the above hack can actually be slightly modified so that it can support displaying the latest tweets from multiple users. The modification is rather simple, and still results in a snippet of self-contained PHP code. Place the following lines of code into a template file where the tweets should appear:

<?php
$usernames = "Profile1 Profile2 Profile3 Profile4"; // Usernames go here, separated by a space.
$limit = "5"; // Define the maximum number of tweets to show
$show = 1; // Change to 0 if account usernames should not be shown, leave set to 1 if they should be
$prefix = "Our Latest Tweets"; // A prefix or heading for the tweets
$prefix_sub = ""; //Prefix for each individual tweet
$wedge = ""; // Separator between tweets
$suffix_sub = "<br>"; // Appended to the end of every tweet
$suffix = ""; // This section of code will be added at the end of the entire list of tweets

function parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub) {

    $usernames = str_replace(" ", "+OR+from%3A", $usernames);
    $feed = "http://search.twitter.com/search.atom?q=from%3A" . $usernames . "&rpp=" . $limit;
    $feed = file_get_contents($feed);
    $feed = str_replace("&", "&", $feed);
    $feed = str_replace("<", "<", $feed);
    $feed = str_replace(">", ">", $feed);
    $clean = explode("<entry>", $feed);
    $amount = count($clean) - 1;

for ($i = 1; $i <= $amount; $i++) {

    $entry_close = explode("</entry>", $clean[$i]);
    $clean_content_1 = explode("<content type=\"html\">", $entry_close[0]);
    $clean_content = explode("</content>", $clean_content_1[1]);
    $clean_name_2 = explode("<name>", $entry_close[0]);
    $clean_name_1 = explode("(", $clean_name_2[1]);
    $clean_name = explode(")</name>", $clean_name_1[1]);
    $clean_uri_1 = explode("<uri>", $entry_close[0]);
    $clean_uri = explode("</uri>", $clean_uri_1[1]);

    echo $prefix_sub;
   
    if ($show == 1) { echo "<a href=\"" . $clean_uri[0] . "\">" . $clean_name[0] . "</a>" . $wedge; }
       echo $clean_content[0];
       echo $suffix_sub;
    }
}
     echo $prefix;
     parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub);
     echo $suffix;
?>

Using the prefixes, the sub-prefixes, and the wedge variable, it's possible to customize the above code pretty easily and make sure that it fits into any context within in an existing website's design. Simply list all relevant Twitter usernames, separated by a space, and each will show their latest tweet within the defined limit set in the code.

5. Detect Visitors From Twitter

Much like some websites detect visitors from search engines and greet them in a unique way, Twitter visitors can be automatically detected as well. This is done in almost the exact same manner as search engine detections, using conditional PHP code to check for a visitor's referral agent and greet them accordingly. here's how it looks:

<?php if (strpos("twitter.com",$_SERVER[HTTP_REFERER])==0) { echo "Hey, Twitter enthusiast! We're glad you're here. If you like what you see, be sure to Tweet about it and follow our account!"; } ?>

This code can be placed wherever the greeting should be displayed. Because it is entirely self-contained, there are no modifications necessary to the "functions.php" file or any other files on the FTP server. Only the template files need to be altered.

6. Enable Tweeting from the Website's Comments

Using a plug-in known as Commentwitter, website administrators can place a Twitter login area below every comment box on the site. When that box is filled in with the right username and password, a comment can be posted to both the website itself, as well as Twitter, instantly and simultaneously.

Commentwitter

Installation and activation are easy; the plug-in will work automatically upon activation, requiring no additional modification to the comments.php template file.

7. Use Twitter Avatars in Comments

Another great way to encourage integration between Twitter and WordPress is to use visitors' Twitter profile pictures as avatars in comments on the site. That's done by using a plug-in called Twittar. The plug-in itself can be found on WordPress.org, within the "Extend" area of plug-ins. It can also be installed directly in the WordPress Dashboard by visiting the "Plugins" page, clicking "Add New", and then searching for the plug-in. Installation will be automatic, and the plug-in will then ask to be activated.

Twittar

Once it has been activated, there's not much that needs to be done to enable the feature. In the "comments.php" template associated with the current theme, place the following line of code in place of any existing WordPress avatar or Gravatar code:

<?php twittar('30', 'default-avatar.jpg', 'X'); ?>

The code above specifies the height and width of the square image, as well as the default image that should be displayed if the commenter does not have a Twitter account. The final variable controls the rating of the image, from G to X, that may be displayed. Because Twittar integrates with both Twitter and Gravatar, the variables above control how images from both services are displayed.

8. Automatically Create Short URLs for Posts in Tweets

With a simple hack to the theme-specific "functions.php" file, WordPress can automatically generate and display short URLs that are perfect for inclusion in Tweets. This hack uses an existing URL shortening service, and comes in two parts. The first part, placed into the functions file, looks like the example below:

function makeBitly($url) {
    $tinyurl = file_get_contents("http://bit.ly/api-create.php?url=".$url);
    return $bitly;
}

With that new function added to "functions.php," a second piece of code must be added to the website's template in order to display the created URL. That line of PHP code must be placed within the WordPress Loop, and it looks like the following:

<?php $burl = makeBitly(get_permalink($post->ID)); echo 'The short URL for this post: < a href="'.$burl.'" >'.$burl.'< /a >' ? >

9. Tweet from the WordPress Dashboard

Though most Twitter integration features are aimed at the public side of a website, it's actually important to enable Tweeting within the WordPress Dashboard, as well. Sometimes administrators require a quick and convenient way to Tweet their followers without actually navigating from WordPress to the Twitter website. In that case, a plug-in available from an independent developer can help.

Twit Twoo

Known as Twit-Twoo, the plug-in allows Tweeting from within the Dashboard by using a modular box on the Dashboard's homepage. Tweets are instantly published to the service once the administrator's Twitter account is linked to it properly.

10. Automatically Create a New Tweet When a New Post is Published

Using the Twitter Tools plug-in, administrators can configure a setting so that a new tweet is posted whenever new post is published in the WordPress Dashboard. Simply install and activate the plug-in, then navigate to the "Settings" area of the Dashboard's sidebar. Click the "Twitter Tools" link and proceed to the Twitter Tools configuration area.

Twitter Tools

Simply fill in the relevant information - including Twitter username and password - and select the option to post a new tweet every time a new post is published. From then on, all of an account's followers will be notified of new content on the website.

11. Create a Page Specifically Used to Display Tweets

Sometimes, Twitter becomes so central to the success of a website that it deserves its own WordPress page. While this might seem a bit intimidating to accomplish at first, it's actually very easy. WordPress is simply told to read the Twitter account's RSS feed and print its content into the page.

To accomplish this, create a new PHP template file called tweets.php and paste the following code into that file:

<?php
/*
Template Name: A Page for Tweets
*/

get_header();

include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://twitter.com/statuses/user_timeline/RSSfilename.rss', 35);

get_sidebar();
get_footer();

?>

The template above will pull in the existing header, footer, and sidebar, largely completing the site's design. It will fill that design in with the last 35 tweets that a user posted. Be sure to edit the RSS feed URL to reflect the proper Twitter account before saving the file.

When the file has been saved to the server, simply add a new page within the WordPress Dashboard and use the right-hand sidebar to select the new template's title as the "Default Template" for the new page. Save any changes, and the all-Tweet page will be ready to go.

12. Post a Regular Blog Entry Containing a Digest of Recent Tweets

Twitter's rise in popularity has meant that many people post several tweets per day, and quite a few per week. This behavior makes it desirable, in some cases, to post a daily, weekly, or monthly digest of all tweets to visitors. They can read those tweets, click on them to view them, and even retweet them if they like.

The best way to do this within WordPress is to use the Twitter Tools plug-in. The plug-in is one of the best ways to deeply integrate with Twitter, and it has its own feature for tweet digests. After installation and activation, browse to the Dashboard's sidebar and find "Twitter Tools" in the Settings area. There, administrators can set their username and log into their account using Twitter's API.

Once that has been completed, an option will appear for tweet digests. In this area, administrators can give the digest a title, set a limit on how many tweets should be included, and determine the appropriate schedule for posting the digest itself. It will then be posted automatically, without further user intervention, and serve as a way to showcase the site's regular tweets.

13. Enable "Tweetbacks" as an Alternative to Traditional Pingbacks

Tweetbacks are a great way to promote WordPress-Twitter interaction. These small snippets of commentary are actually pulled into a website whenever a user on Twitter posts a tweet linking to a blog's posts. The "tweetback" is then posted in the comments area, enriching the site with a bit of social engagement.

Tweetbacks

To enable this feature, administrators will need to install the Tweetbacks plug-in from WordPress.org, or from within their Dashboard. A few configuration settings will need to be defined, and then the plug-in will be ready to go with a simple template modification in the comments.php file.

14. Display the Latest Tweet as an Image

A service known as TwitSig is actually capable of reading an account's tweets and then processing them into an image that can be included in forum signatures, emails, and WordPress templates. This is a great way to show tweets without having their content impact the site's SEO with major search engines. To do this, simply go to Twitsig.com and sign up according to the website's instructions.

Then, anywhere within WordPress, add the following code:

<a href="http://twitter.com/YourProfileUsername">
<img src="http://twitsig.com/YourProfileUsername.jpg" alt="Image of Tweets" title "Image of Tweets" class="tweetImage" />
</a>

15. Show a Retweet Button with a Counter with Each Post

While a "Tweet This!" button is a great way to encourage user engagement, an even better tool is a retweet button with a counter. This button allows for easy sharing of a website's content to the social network, and it will keep count of how many people have done so. The code snippet is pretty brief, and looks like this:

<script type="text/javascript">
tweetmeme_source = 'YourTwitterUsername';
</script>
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js" ></script>

Once customized with the Twitter username of the website's administrator, it will begin keeping count of all the post's retweets on the popular social network.

16. Add a News-Style Ticker of Tweets to the Site

One of the best ways to conserve space and keep readers up to date about activities on Twitter is to add a ticker to the site that rotates the latest tweets like a typical news ticker does. Best of all, this is easy to accomplish with a basic WordPress plug-in known as My Twitter Ticker.

Twitter Ticker

Simply install and activate the plug-in, and then go to the "Widgets" panel within the "Appearance" area of the Dashboard. Add the widget to the existing sidebar and enter all of the Twitter usernames, separated by commas, that should show up in the ticker's feed. Save the widget, and the changes will appear on the website immediately. Best of all, the ticker uses a slick jQuery implementation for smooth effects and transitions, meaning it will instantly appear professional to the site's visitors.

Lots of Great Options for Integration

Twitter is a growing social network with a growing number of implications. Websites that fully embrace the service and integrate with it will be rewarded with increased traffic, better SEO, and more repeat visitors.

Those who don't will quickly fall behind. Because each of these hacks is basic, with some only requiring a plug-in, they should be quickly implemented so that a website can take advantage of all of Twitter's features.

Note: Some of the plugins or techniques may not work anymore due to Twitter updates and changing API. You can stay abreast of what's going on at Twitter Developer Blog and feel free to suggest the latest way for Twitter integration with your WordPress site.