How To: Twitter Bar, Popular Posts, Random Stats

June 3, 2007

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?

Paul Stamatiou runs on the Genesis Theme Framework

Genesis Theme Framework

Genesis empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go.

Take advantage of the 6 default layout options, comprehensive SEO settings, rock-solid security, flexible theme options, cool custom widgets, custom design hooks, and a huge selection of child themes ("skins") that make your Genesis site look the way you want it to. With automatic theme updates and world-class support included, Genesis is the smart choice for your WordPress website or blog.

47 comments … read them below or add one

  1. zzap says:

    That Twitter thing is handy. Thanks.

  2. Marvin Sum says:

    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. bandersnatch says:

    Thank you for sharing, Paul.

    I’ll be incorporating some of these mods shortly.

  4. Ryan Powell says:

    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’));

    • Thanks for this tip! I was having an issue with this code on my blog.
      It wouldn’t update like it was supposed to.
      It works great now, only showing posts in the last month.
      Thanks Richard (& Paul)!

      -Joe

  6. Dimitry says:

    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. Brian Heys says:

    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. Alex says:

    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. Adam says:

    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. Jessie says:

    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. Adam says:

    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. Jessie says:

    @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. outsider says:

    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. Mike Malone says:

    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. Kickass Mike!

  24. Micahville says:

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

  25. Micahville says:

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

  26. Adam says:

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

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

  27. Astorg says:

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

  28. Mike Malone says:

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

  29. Alex says:

    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

  30. 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.

  31. David Moore says:

    “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

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

  33. Adam says:

    @ 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.

  34. georgeadams says:

    “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

  35. James Wong says:

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

  36. 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.

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

  38. Ralph Dagza says:

    can you teach me how to do this?

    http://nixonnow.org/

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

  39. Stefaan says:

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

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

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

  42. Jason says:

    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!

  43. Penny Butler says:

    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> ";

  44. Hi Paul,

    Good post. You are right that the sidebar Twitter gives me takes forever to load. I think it is flash based and it never loads when I view the blog on the iPhone since that can’t support flash.

    I’ll check out the plugin from Mike. Doesn’t Twitter have an HTML version of the Twitter updates for the sidebar too though?

    ~ Joel Mark Witt

  45. eago says:

    I’ve been looking for how to do this, Thanks.

  46. jalmz says:

    what about Popular post this month with Comments Count?

68 Trackbacks

  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. 韶华白首 says:

    【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. [...] Показываем Twitter посты на WordPress [...]

  21. [...] 37. Display Twitter messages in WordPress [...]

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

  23. [...] Display Twitter messages in WordPress [...]

  24. [...] 别让你最重要的信息因为不断更新而在数据存档中淹没。 37.在你的WordPress上显示Twitter消息 [...]

  25. [...] 37.在你的WordPress上显示Twitter消息 [...]

  26. [...] Display Twitter messages in WordPress [...]

  27. [...] 36.如何将你最重要的内容展示在前别让你最重要的信息因为不断更新而在数据存档中淹没。37.在你的WordPress上显示Twitter消息通过自定义让你的WordPress博客显示你的Twitter消息。 [...]

  28. [...] 在wordpress中顯示Twitter訊息 在你的wordpress部落格中自訂Twitter訊息的顯示 [...]

  29. [...] WordPress是强大的,尤其是你用插件将其武装起来。Hongkiat在博客上写了40个Wordpress里的技巧,相信大多数使用wordpress的Blogger都不会满足于默认模板、默认的设置。应用这些技巧,你能将WP改装得更漂亮,更个性化。1、类别下拉菜单分类太多,但又想展示全部展示出来,不妨考虑用下拉菜单的方式展示,和可能吧菜单栏上的“更多”有点类似。2、显示作者Gravatar头像有些博客是多作者的,如果你觉得单是一个名字不能明显地区分作者,不妨考虑将头像也加上。3、自定义首页用一个自定义的页面替换默认的/index.php首页。4、显示文章作者信息还是多作者博客可能需要使用的技巧,在每篇文章中都显示该篇文章作者的信息。5、显示某一类别的最新评论只显示某类别的评论,而不是全部。6、高亮作者评论在评论里,用特别的颜色将文章作者的评论高亮起来。7、文章缩略图为每篇文章创建一个缩略图,让你的文章看起来更有趣。8、分类图片用图片替代分类的文字。9、阅读器图片格式优化有时在阅读器里文字和图片会出现下面的情况:如果出现了,你需要学学怎样去解决。10、日期按钮:制作一个小巧的日记按钮。11、某篇文章隐藏广告某些文章或许你不想显示广告,比如写关于腾讯的,会出现大量所谓的“6位QQ号”广告。12、文章置顶给某篇、或某些文章设置置顶。13、自定义404错误网页或许你看了15个很有创意的404页面后很想自己做一个刚有创意的,试试吧!14、将Wordpress打造成成员目录如下图:15、加速Wordpress的4个基本方法觉得你的博客加载速度很慢而导致博客冷清?尝试用精简代码等方法加速WP吧。16、创建博客手机版为WP博客创建一个手机版本17、新窗口打开链接大多数默认情况下WP文章里的链接是在原窗口打开的,你可以尝试更改为在新窗口打开。18、将WP打造成CMS将WP打造成一个杂志型网站。19、制作翻页效果在博客右上角(或其它地方)制作翻页效果,然后放点即时小时也不错。20、将评论与引用分开这个很有必要,有些博客评论区域里评论和引用混乱在一起,看起来不是很友好。21、Wordpress增强编辑器默认的WP编辑器非常简陋,不妨考虑换一个,比如FCKeditor。22、侧栏登录将登录框搬到侧栏中去。23、图片防盗链文章被转载时很多情况下图片都会被复制粘贴去,如果你是将图片上传到自己的空间,而你的服务器又没有安装防盗链软件,你可能需要使用这个防盗链插件。24、在第一篇文章放置广告有调查表明,浏览者看第一篇文章时点广告的几率最大。你可以设置广告只出现在第一篇文章,后面的文章就不出现,如果你放置了太多广告影响浏览体验的话。25、自定义登录界面登录页面虽然只是自己看的,但你也可以将其弄得漂亮点,登录后或许能有个好心情,写篇好文章。26、将优秀的文章秀出来酒香也怕巷子深,好的文章不妨拿出来给别人看。27、展示Twitter消息在博客里展示Twitter消息。(不是简单的嵌入twitter提供的代码)28、字数统计你应该需要知道一篇文章有多长的。29、某些内容只在Feed提供你可以用这个插件,在Feed里提供一些特别的内容,以鼓励订阅。30、某一分类不出现在Feed里(中文)有时我们不希望所有的分类都输出到Feed里。原文地址:http://www.kenengba.com/post/464.html [...]

  30. [...] 在wordpress中显示Twitter讯息 在你的wordpress部落格中自订Twitter讯息的显示   [...]

  31. [...] Stamatiou has code snippets required to pull in Twitter status to, and list random stats on your blog, [...]

  32. [...] 11. How To: Twitter Bar, Popular Posts, Random Stats [...]

  33. [...] 37.在你的WordPress上显示Twitter消息 [...]

  34. [...] 别让你最重要的信息因为不断更新而在数据存档中淹没。 37.在你的WordPress上显示Twitter消息 [...]

  35. [...] 37.Display Twitter messages in WordPress [...]

  36. [...] Display Twitter messages in WordPressCuztomize the Twitter message display on your WordPress blog. [...]

  37. FAQPAL Blog says:

    [...] Source… [...]

  38. [...] 27. How To: Twitter Bar, Popular Posts, Random Stats [...]

Leave a Comment

*

Leaving so soon?

Don't forget to check out the Reviews and How-Tos, or read a random post.