Twitter: jegs.com doesnt know how to handle payments. 3 days of paused order and bunch of calls [...]

How To: Twitter Bar, Popular Posts, Random Stats

Jun 03, 2007 in , ,

Every week I receive more than a handful of emails from people asking me what I use to display my Twitter status on this blog, as well as how I do the “popular this month” block and display random blog stats in my sidebar. Hopefully this post will answer those questions.

Twitter Status

First off, Twitter has their own method for displaying your Twitter status on your website but they rely on Twitter-hosted scripts and generally hold up the page load. There is also Alex King’s Twitter Tools Plugin for WordPress but the general consensus is that it’s complex and takes customization to get it working like mine is.

As such, I use Dave Kellam’s twitterRSS WordPress plugin. It’s more of a hacky script than a plugin and last I checked, doesn’t have any fancy admin panel page - but it works. It relies on the built-in RSS parser of WordPress which is used in the dashboard, so it will only update when that updates.. each ~1 hour. As Dave mentions, using it is as simple as a single PHP function call once the plugin is enabled. However, I like to expand on that so that your page doesn’t get killed if you accidentally disable the plugin:

<?php if(function_exists('get_twitterRSS')){get_twitterRSS();} ?>

Update: Mike Malone has added a few features to this plugin: http://immike.net/scripts/twitterrss.txt.

Popular Posts This Month

Instead of going by traffic for specific posts, the “popular posts this month” block in my sidebar goes by the number of comments on articles within the last month. I used the most commented plugin and adapted the SQL query to account for a time range. Here’s the code:

<?php
$now = gmdate("Y-m-d H:i:s",time());
$lastmonth = gmdate("Y-m-d H:i:s",gmmktime(date("H"), date("i"), date("s"), date("m")-1,date("d"),date("Y")));
$popularposts = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'stammy' FROM $wpdb->posts, $wpdb->comments WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish' AND post_date < '$now' AND post_date > '$lastmonth' AND comment_status = 'open' GROUP BY $wpdb->comments.comment_post_ID ORDER BY stammy DESC LIMIT 6";
$posts = $wpdb->get_results($popularposts);
$popular = '';
if($posts){
foreach($posts as $post){
$post_title = stripslashes($post->post_title);
$guid = get_permalink($post->ID);
$popular .= '<li><a href="'.$guid.'" title="'.$post_title.'">'.$post_title.'</a></li>';
}
}echo $popular;
?>

That code displays the 6 most popular posts. You can change the number of posts displayed by altering the number in the SQL query where it says "LIMIT 6".

Random Stats

This one became so popular and frequently requested that Mike Malone ended up making a WordPress plugin around it. My solution is rather simple: use rand() to create a random number and have a different action assigned to each number. I ended up using a bunch of else if’s but in hindsight a switch-case statement might have been nicer.

The first section displays the total number of words blogged in the number of days your blog has been active. I hard coded the date I started my blog in there, so you’d have to change that. The next section displays the total number of posts and comments. The third section displays the number of spam comments killed by Akismet (I edited the Akismet plugin to remove CSS/images and only output a number). Finally, I have a link to PSTAM.com but you can change that to anything really. The structure is fairly easy to grok even if you’re not a super coder.

<?php
$var = rand(1,4);
if($var==1){
function word_count(){global $wpdb;$now = gmdate("Y-m-d H:i:s",time());$words = $wpdb->get_results("SELECT post_content FROM $wpdb->posts WHERE post_status = 'publish' AND post_date < '$now'");if($words){foreach($words as $word){$post = strip_tags($word->post_content);$post = explode(' ', $post);$count = count($post);$totalcount = $count + $oldcount;$oldcount = $totalcount;}}else{$totalcount=0;}echo number_format($totalcount + $titlecount);}
word_count(); echo " words blogged in ".round((time() - strtotime('september 8 2005'))/60/60/24)." days";
} else if($var==2){
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");if (0 < $numposts) $numposts = number_format($numposts);$numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");if (0 < $numcomms) $numcomms = number_format($numcomms);
echo $numposts . " posts and " . $numcomms . " comments";
} else if($var==3 && function_exists('akismet_counter')){
akismet_counter(); echo " spam killed by Akismet";
} else if($var==4){echo "Can't spell my name? Use ";?><a href="http://pstam.com">PSTAM.com</a><?php } ?>

Any other requests?

Promote this article on various sites or email to your friends:     



83 Comments

  1. That Twitter thing is handy. Thanks.

  2. Yea, I’ve got one. If you asked Wordpress to display, say, 15 items per page, how do you modify the loop on your homepage so it displays a different number (say 10?)

    Cheers Paul.

  3. Thank you for sharing, Paul.

    I’ll be incorporating some of these mods shortly.

  4. I’ll have to try the twitter one out, I’ve been using the twitter scripts that def. tend to hold up my page load.

    Thanks

  5. Good stuff, Paul.

    Is there any reason you don’t use strtotime() for things like getting last month? And is there any reason to use gmdate() instead of date()? Something like this would be my first thought:

    $now = date(’Y-m-d H:i:s’);
    $lastmonth = date(’Y-m-d H:i:s’, strtotime(’-1 month’));

  6. Popular this month is really cool. Really liked/like that addition

    @Marvin Sum: There’s a variable you can put inside your index.php just before the loop, forgot what it is though. $Max_Posts or something of that sort, just check out the support WP forums.

    Dimitry

  7. I added Twitter to my blog’s header a couple of days ago, and am making use of a WordPress plugin called ‘SimpleTwitter’. So far, I’m pretty impressed with it. It was easy to install, and has a control panel facility, so no hacking around with PHP to incorporate your twitter ID, etc.

  8. You read my mind :-) Will reply to your emails in a day or so, should be ready to launch then!!!

  9. There is also Alex King’s Twitter Tools Plugin for WordPress but the general consensus is that it’s complex and takes customization to get it working like mine is.

    Hmm, first I’ve heard of it. Perhaps you can mail me a description of the issues.

  10. Many thanks for that, I have been meaning to ask you how you did the twitter thing for a few weeks.

    BTW, have you considered disabling the “nofollow” attribute for the comments on this page? Quite a lot of the regular commenters on this site would like to get to #2 (on Google) too!

  11. Err this is gonna sound stupid but for that bit of code from Popular Post this Month, do I just insert the code wherever I want the popular posts to show up? Thanks.

  12. @Jessie - I created a PHP enabled sidebar box and added the code into that, then positioned it where I want it on the sidebar.

    ‘Unfortunatley’ it is on the site I am developing but I also added it to http://www.almerimarlife.com

  13. For twitter I used this code:

    The only problem, is if there’s any problem with twitter feed, he rest of the site doesn’t load right.

    Maybe I’ll change to your way!
    Thanks for sharing this!

  14. ops, here goes the code:

    <?php
    preg_match(’#(.*)#’,file_get_contents(’http://twitter.com/statuses/user_timeline/username.xml?count=1′), $matches);
    echo $matches[0]
    ?>

    :)

  15. Has anyone actually managed to get the “hide_links” or “hide_username” bits working? Currently not matter what I set them as, it hides my links by doesn’t hide the username.

  16. @Chris Marshall: Thanks. I was pretty sure that was it, but then I didn’t want to mess anything up. :)

    And thanks for the post Paul. REALLY useful.

  17. thanks paul. Still some problem with the recent comment thing, but I’ll try to fix it.. thanks anyway

  18. @Richard - I’m not exactly sure why as I wrote it a long time ago, maybe I ran into some problem and tried the gmdate, or I just didn’t know that much about PHP when I wrote it.

    @Daniel, I like your method but it still accesses twitter.com on the fly and will add another HTTP request. Although I don’t think it would be that hard to cache the XML for a few minutes.

  19. @Alex King, personally I’ve only used Twitter Tools briefly but this is an example of the type of email others send me:

    “I was just wondering which WordPress plugin you use to put your Twitter status on your blog. I’ve been using Twitter Tools but it doesn’t seem as customizable as yours looks.”

  20. I don’t use wordpress… but I am sooo tempted to switch. :)

    Awesome how to! the only minor quibble is that the code isn’t really formatted nicely- but not a real big issue as you can copy/paste it easily.

    Thanks Paul!

  21. @titanium_geek - that’s an issue I’ve been struggling with for a longtime. I’m trying to go about it without any plugins b/c I had a plugin I used all the time that stopped working and was no longer developed and I had to go back through my posts and change markup. I was considering using

    
    

    tags but then the code doesn’t like line-wrapping - there is a way to force it but it’s not standards compliant.. I’ll have to dig deeper.

  22. Great post Paul. I grabbed the twitter plugin and fixed a few things / added some features.

    I added URL replacment, like twitter does on their site. So if you have a URL (like http://paulstamatiou.com) in your twitter it will be replaced with a hyperlink. I also added @reply replacment, so the username in an @reply links back to that user’s twitter page. Last, I added a trim function so you can trim your twitter to a particular length (I didn’t want mine wrapping onto another line).

    @Adam: I also fixed a little bug with $hide_links, you may want to take a look (hint: replace $twitters with $twitter in the source). The “username replacement” is really just stripping whatever the name is at the beginning of your twitters. Mine isn’t my username, it’s my real name, so I put “Michael Malone” as my username and it works.

    Finally, I commented a bunch of stuff so people can actually make some sense of the plugin without looking at the code. Adding an admin panel wouldn’t be hard, but I’ve got to pack so I can’t do it now… maybe some other time.

    You can grab my new version here. Change the extension to .php when you put it on your server, of course.

  23. Thanks for the shout out to Mike, Paul. I implemented his plugin and discovered a great new blog. Gracias!

  24. P.S. Offtopic, BUT you have to be 21 to rent a car in California. Have fun, and get a good one!

  25. Mike- well done on fixing that, it works, yay! Nice site by the way.

    Paul- Many thanks for letting me troubleshoot via your website!

  26. The Twitter function works in English, but not in French, because it renders accented characters as question marks.

  27. @Adam & Michaville: Thanks for the props. I’m glad I could help!

  28. The 1.0 release of Twitter Tools has a template tag to show just the latest tweet:

    http://alexking.org/projects/wordpress/readme?project=twitter-tools

  29. Thanks Paul,

    I have always wondered how to add twitter to my site without the ugly sidebar status they recommend.

    Request
    You should also write a how-to use the CSS bubbles for comments.

  30. “Any other requests?”

    Yes keep em coming! :)

    Been waiting for you to write a post like this for a while its really useful! Top commenters would be could as a couple of plugins i tried for that didnt work.

    Dave

  31. ooh ooh- I second Blake’s request for the css comment howto.

  32. @ Blake & titanium_geek: I thought I had seen Paul already write about this, but I can’t find it though the Archives. Either-way, he uses this bit of coding: http://www.willmayo.com/2007/02/10/css-speech-bubbles/

    Hope that helps.

  33. “Any other requests?”

    I’ ve got one! :) how can we show the post date bellow the post title in the “popular posts this month” thingie?

    By the way, thanks for another great post!

    George

  34. regarding twitterrss, which template should i insert “” to? i tried putting it somewhere on header.php but nothing shows up. pardon my noobity.

  35. Thanks for the tips! I’ve added the Twitter widget on my site as well. Only think that is kinda lame is that it take a while for it to refresh its content. I previously was using this method: http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/ but I like the one you use better since it works well with all browsers.

  36. dude, this things is awesome! it’s exactly what i was looking for..thanks!

  37. can you teach me how to do this?

    http://nixonnow.org/

    i want to put my twitter stat on a non wordpress site

  38. Great tip for the twitterRSS plugin but my tweets are not loading?

  39. It seems I’ve used your way now :)
    Thanks

  40. great post… I added the twitterrss to my site. thanks!

  41. Hi, I love the Twitter plugin. I was wondering how to get it to spit out each “twitter post” in an ? I don’t really know much about PHP so I’m really confused.

    Anyone know how to accomplish this? Thanks!

  42. Hiya,

    Great plugin, just wonderng how you got “Twitter:” to be linked to your twitter site?
    It doesnt seem to like the a href.. but I can bold my “Twitter:” etc.. but gives a fatal error when I attempt to add:

    // HTML or text to display before and after each twitter
    $before = " <a href="http://www.twitter.com/happyches"><b>Twitter:</b></a> ";

  1. [...] How To: Twitter Bar, Popular Posts, Random Stats - PaulStamatiou.com Paul rovid, amde hasznos irasa arrol, hogy jelenitsuk meg a twitter uzeneteinket a blogunkon. (tags: twitter rss wordpress wp hack code paulstamatiou) [...]

  2. [...] How To: Twitter Bar, Popular Posts, Random Stats - PaulStamatiou.com (tags: twitter how-tos code) [...]

  3. [...] Textos Populares/Mais lidos: essa eu peguei do Paul Stamatiou. Tudo feito via codificação sem plugin nenhum! How To: Twitter Bar, Popular Posts, Random Stats. [...]

  4. [...] This is the plugin that Paul Stamatiou says he uses to load his tweets on his site. That being the case, I thought I would give it a shot. This plugin isn’t as [...]

  5. [...] There are many Twitter tools for WordPress blogs, but the one I use is a modified version of twitterRSS that you can download from here (found via Paul’s blog). [...]

  6. [...] Like the Facebook feature, of the “status update”, Twitter lets you send “updates” of up to 140 characters of text to the Twitter website. You can use the site to do this, or SMS, IM or third-party applications. You can also follow other people, and receive their updates on the website, via RSS or using an application like the OS X client Twitterrific, created by The Iconfactory. Without it I would have not been told by Jon Hicks about the existence of more than one Lemon Jelly album. I have also managed to tie my Facebook status and Twitter together using the TwitterSync application, and at some point I will also be adding Twitter updates to WilcosWorld, following Paul’s tutorial. [...]

  7. [...] Display Twitter messages in Wordpress [...]

  8. [...] 27、展示Twitter消息 [...]

  9. [...] Display Twitter messages in Wordpress [...]

  10. [...] Muestra los mensajes de twitter en tu blog [...]

  11. [...] 37. Mostrar mensajes Twitter en Wordpress. [...]

  12. [...] Display Twitter messages in Wordpress [...]

  13. [...] 27、展示Twitter消息 [...]

  14. [...] Display Twitter messages in Wordpress [...]

  15. [...] Muestra los mensajes de twitter en tu blog [...]

  16. [...] 3. Twitter Messages Display Twitter Messages. Could get you more followers! Homepage [...]

  17. 【WP常用技巧翻译】如何建立Twitter信息栏,受欢迎日志,随机博客统计…

    原文地址:How To: Twitter Bar, Popular Posts, Random Stats
    WordPress 常用技巧40+则,诚邀您的参与翻译(第37篇)
    翻译者:hitigon 水平有限,欢迎纠正文中错误!
    转载请注明原文及译文地址,尊重作者劳….

  18. [...] 27、展示Twitter消息 [...]

  19. [...] 20. How to Display Twitter messages in Wordpress [...]

  20. [...] 27、展示Twitter消息 [...]

  21. [...] Показываем Twitter посты на Wordpress [...]

  22. [...] 37. Display Twitter messages in Wordpress [...]

  23. [...] 37. Display Twitter messages in Wordpress [...]

  24. [...] Display Twitter messages in Wordpress [...]

Post a comment, receive Stammy points.


Send a trackback.


  • If you plan on posting code, run it through Postable first.
Copyright © 2005 - 2008 PaulStamatiou.com  Privacy Policy - Terms of Service Can't spell my name? Use PSTAM.com. Go back up ↑.