Fetch Twitter Count for WordPress

Looking for an easy way to include your current Twitter count in WordPress? Here’s a simple piece of code I’m using to fetch and display the current Twitter count, it includes transient caching of one hour for your most recent Twitter count.

/**
* Summary returns the current follower count of a specific Twitter account, or FALSE if not found
* @param String $twitter_username the username you wish to get a Twitter count for
* @param Number $transient_cache the time in seconds to cache the transient (default is one hour)
* @return String an unformatted number of followers from twitter
*
* @author Christopher Ross (@thisismyurl)
* @version 1.0.0
*/
function thisismyurl_twitter_count( $twitter_username = 'thisismyurl', $transient_cache = 3600 ) {

$current_twitter_count = get_transient( 'thisismyurl_twitter_count' );

if ( empty( $current_twitter_count ) ) {

$xml = file_get_contents ( 'http://twitter.com/users/show/' . $twitter_username );

if ( $xml ) {
$twitter_profile = new SimpleXMLElement ( $xml );
$current_twitter_count = $twitter_profile->followers_count;

if ( !empty( $current_twitter_count ) )
set_transient( 'thisismyurl_twitter_count' , $current_twitter_count, $transient_cache );
} else {
return FALSE;
}

}

return $current_twitter_count;

}

To display your current Twitter count in your WordPress theme, include the code:

if ( function_exists( 'thisismyurl_twitter_count' ) )
echo thisismyurl_twitter_count( 'thisismyurl', 3600 );

If the count can not be returned, the function will return FALSE which allows error checking such as:

if ( function_exists( 'thisismyurl_twitter_count' ) ) {

$twitter_count = thisismyurl_twitter_count( 'thisismyurl', 3600 );

if ( $twitter_count )
echo 'Twitter Count:' . $twitter_count;
}

What do you think? Is there a way to improve this function?

How to change a WordPress theme with PHP

There are times when a programmer needs to change a theme using PHP rather than using the WordPress administration tool, this little piece of code will allow you to do that by placing it in your functions.php file.

add_action( 'template_redirect' , 'thisismyurl_change_theme_manually' );
function thisismyurl_change_theme_manually() {
if ( 'twentyeleven' != get_current_theme() )
switch_theme( 'twentyeleven', 'style.css' );
}

Update: Nacin (@nacin) pointed out a couple fixes for this piece of code. First, the get_current_theme() is depreciated, so get_stylesheet() is a better function to use and secondly, running this on the front end of the site isn’t the best idea.

With that in mind, here’s the revised code.

add_action( 'template_redirect' , 'thisismyurl_change_theme_manually' );
function thisismyurl_change_theme_manually() {
if ( 'twentyeleven' != get_stylesheet() && is_admin() )
switch_theme( 'twentyeleven', 'style.css' );
}

You can read more from Andrew Nacin at nacin.com.

Assign a Template to a Page and all Child Pages

An interesting question popped up the other day while I was developing a theme for a WordPress website. The client wanted to load a specific template for a specific page, as well as all of the child pages. For example, the About Us section but also the Contact Us (assuming it was a child of About Us).

If they’d just wanted to load a single page template, I would refer to the default hierarchal structure and simply create a theme file named page-[slug].php but how to do it for each of the subsection pages as well? On Friday when I wrote the a piece on redirecting WordPress based on the URL, it occurred to me that there are a couple really easy ways to do it.

Here’s my solution:


add_action( 'template_redirect','thisismyurl_about_template_override' );
function thisismyurl_about_template_override() {
if (  strpos( $_SERVER['REQUEST_URI'], '/about-us' ) > 0 ) {
include ( TEMPLATEPATH . '/page-about-us.php');
exit;
}
}

So what’s it do? Simply put, it waits until after WordPress has loaded everything it needs to load to run smoothly, then just before WordPress tries to load the theme file we intercept the logic and force it to load page-about-us.php instead.

Random Post WordPress Redirection

This morning I came across a fantastic post on Smashing Magazine dealing with WordPress redirection and how to create a random redirect for visitors to your website. The post is absolutely correct in its method for creating a redirect as presented but there’s a slightly more elegant approach I’ve learnt with building newspaper websites with WordPress, and that’s to use a hook.

A hook is a means in WordPress to override the default functionality of WordPress and in this case, what we want to do is force WordPress to redirect before it’s even begun loading all the extra logic. To do that, we’ll tap into the template_redirect function. This function loads immediately after the website is initiated but before the theme file is loaded. It’s a perfect place to do things like redirect a page or, (as the name implies) the template. For example if you want to override a post or page template, this is where you can do it.

I’ve made two other small edits to the Smashing code example. First, I’ve added the redirect 302 value to the wp_redirect() function to tell Google that this is a temporary redirect (301 would be permanent) and I’ve combined the array for get_posts() into a single line as we won’t be reusing the variable.

add_action( 'template_redirect','thisismyurl_random_post' );
function thisismyurl_random_post() {
if (  '/random-post' == $_SERVER['REQUEST_URI'] ) {foreach ( get_posts ( array( 'numberposts' => 1, 'orderby' => 'rand' ) ) as $post ) {
wp_redirect ( get_permalink ( $post->ID ) , 302 );
exit;
}

}
}

Simply place this bit of logic in your functions.php file and you’ll be able to randomly redirect people to articles using a URL such as http://thisismyurl.com/random-post

How Yoda Saved My Blog

To be fair, while I would love to give all the credit to Yoda, I feel that I have to come clean and admit that it was in fact Chip Bennett who pointed out how to use Yoda Conditionals at WordCamp last weekend. What’s amazing however, is how quickly you can put new knowledge to use and how much time it saves.

What is a Yoda Conditional?

In PHP (the language WordPress is written in) we can compare a variable to a value by using an if statement to construct a question like so:

if ( $myname == 'Christopher') do_something();

Now when you want to assign a value to a variable in PHP you simply write:

$myname = 'Christopher';

Which, if you’re in a hurry will sometimes lead you to accidentally type:

if ( $myname = 'Christopher') do_something();

Now, instead of comparing the value $myname to the string Christopher, the statement will set $myname to equal Christopher … technically your code will run, but it’ll not do what you thought it should do. The solution that Chip showed at WordCamp was to simply invert the comparison to read:

if ( 'Christopher' == $myname ) do_something();

By doing this, you’ll ensure that the comparative function will still work but switching the == for an = by accident will break your website and reveal the error, saving your hours of frustration and sifting through code. Not as clumsy or random as a regular comparison; an elegant solution for a more civilized age.

Needless to say, it’s an easy way to avoid headaches and this morning it saved me from uploading an error to thisismyurl.com that would have broken the Easy Popular Posts widget.

Show a daily quote in WordPress from an external file

How do you load an external file into WordPress and display the results based on a specific date? That was the question in a forum today and luckily, with a quick update to some pre-existing code samples for WordPress I was able to help the blogger meet his goals.

First, I took the code from Display a Random Header in WordPress and combined it with some pre-existing PHP to put together this little piece of code:


function thisismyurl_todays_quote() {
$header_dir = TEMPLATEPATH.'/quotes/';
if ($handle = opendir($header_dir)) {
while (false !== ($file = readdir($handle))) {
if ($file == date('z').".txt") $quotetext = file_get_contents($file);
}
closedir($handle);
}
if ( !empty( $quotetext) ) echo $quotetext;
}

Now just add this code to your functions.php file along with a directory called quotes to your theme directory. Add 365 files named numberically (1.txt, 2.txt etc) to your quotes directory and you’re almost done.

Where you want the quotes to appear, add thisismyurl_todays_quote() to your PHP. For example, if you want it in your footer just add <?php thisismyurl_todays_quote();?> to your footer.php file and the script will load a quote based on today’s file.

This is a pretty quick code snippet, I’m sure there’s other (better) examples on the web. If you come across a better solution, please link to it in the comments below.