Adam Green
Twitter API Consultant
adam@140dev.com
781-879-2960
@140dev

Fun with WordPress code and tweet aggregation

by Adam Green on October 9, 2010

in Integrating Twitter with Wordpress,Tweet Aggregation

I had an interesting time getting the Twitter developer tweets onto a WordPress page. I explored lots of different paths:

  • My first attempt was to use a plugin called Exec-PHP. This worked fine as a way of getting the tweet list to appear on a WordPress page, because I have the display code callable by a single PHP include. The problem is that this plugin only lets me add code to the content of the page, which appears in the HTML body. I also need to add CSS and JS files to the page head.
  • I next tried writing my own plugin that could insert the CSS and JS in the head, and the include in the body. I got that to work, but found a problem with the CSS and JS files. The method everyone recommends to add code to a WordPress page head is to tie this to the init action. Unfortunately, init is called for every page, so the result of this new plugin was to insert a CSS and JS file load into every page on the site. This is an unnecessary performance hit that I was not willing to accept.
  • So I tried adding is_page() tests to the functions that load the CSS and JS files to the head, and the function that includes the tweet list into the content of the page. I only want to include the CSS and JS files on the tweet aggregation page. I found out that the init hook happens before WordPress knows what page is loaded, so is_page() fails in a function called by the init hook.
  • I spent almost an entire day reading everything written about this problem, only to find that none of the posted solutions worked. I then tried every WordPress hook to find one that allows code to be inserted into the page head and also works with an is_page() test. I finally found that the wp_enqueue_scripts hook does the job. Funny that nobody recommends this, but it does seem to work.
  • So now I have a plugin that can insert the the CSS, JS, and tweet list onto a single specified page. But how do I specify that page? I could write the page name into the plugin code, but that means editing the plugin script to adapt it to each site where the tweets are displayed. That makes me queasy, so I decided to save the page name in a config file I already use to store parameters for the tweet display, like the refresh interval, and the number of tweets to be displayed. This can now be edited to control the insertion of the tweet aggregation in a WordPress site. It still seems like a hack, but I’m using this plugin just for my site. When I get around to open sourcing this plugin, I’ll build a plugin settings page, so users can easily enter the page name for the tweet display.

Previous post:

Next post: