Twitter Followers Count Snippet for WordPress

UPDATE: This code no longer works as Twitter retired v1.0 of their API. v1.1 of their API requires authentication in order to access it. I have no plans to update this code for their new API. Sorry.

Konstantin Kovshenin posted some code on his blog for how to display how many Twitter followers someone has. While the idea was good, I think he went about the implementation in the non-best method. So, for fun and because I don’t post enough code snippets here on this blog, I thought I’d post how I would display how many followers someone has on Twitter. 🙂

function viper_twitter_followers( $username = 'Viper007Bond' ) {

	// Just to keep the code below cleaner, create the cache key now
	$cache_key = "viper_twitter_followers_{$username}";

	// First we look for a cached result
	if ( false !== $followers = get_transient( $cache_key ) )
		return $followers;

	// Okay, no cache, so let's fetch it
	$result = wp_remote_retrieve_body( wp_remote_get( 'http://api.twitter.com/1/users/show.json?screen_name=' . urlencode($username) ) );

	// Check to make sure we got some data to work with
	if ( empty($result) ) {
		// Cache the failure for 1 min to avoid hammering Twitter
		set_transient( $cache_key, 0, 60 );
	}

	// Parse the data
	$data = json_decode( $result );

	// Make sure we were able to parse it
	// If not, cache the failure (like above)
	if ( !isset( $data->followers_count ) )
		set_transient( $cache_key , 0, 60 );

	// Success! Cache the result for an hour.
	$followers = (int) $data->followers_count;
	set_transient( $cache_key, $followers, 3600 );

	return $followers;
}

echo 'I have ' . viper_twitter_followers( 'Viper007Bond' ) . ' followers on Twitter!';

Reading Material:

If you have any questions about the above code, let me know and I’ll do my best to answer them. 🙂

Tracking WordPress Remote HTTP Requests

UPDATE: You can find improved code in this newer blog post. Use that instead.

I thought I’d share a bit of code that I run on my local WordPress test install to see when WordPress is contacting another website. I originally wrote this to help debug my oEmbed code, but it’s useful for a wide variety of purposes. 🙂

<?php

if ( !defined('DOING_AJAX') )
	add_filter( 'http_request_args', 'debug_http_api', 10, 2 );

function debug_http_api( $r, $url ) {
	echo '<p style="text-align:left">HTTP API was used to fetch <code>' . esc_html( $url ) . '</code></p>';

	return $r;
}

?>

The above code will output something like this any time a HTTP request is made using the HTTP API, but only if the request was not made from an AJAX handling script (as it will break the AJAX response):

HTTP API was used to fetch http://www.google.com/

While I’m using a filter to do this, I’m actually using the filter much like an action as I’m not modifying the passed data but merely using the filter as a place to hook in and catch the URL.

WordPress: Using Filters With get_posts()

Something I just learned and thought I’d share to save others the trouble: if you’re attempting to filter the results of get_posts(), for example with the posts_where filter, you need to disable suppress_filters.

For example, here’s how to fetch some posts from within the past 30 days (based on an example from the Codex):

<?php

function last_thirty_days( $where = '' ) {
	global $wpdb;

	$where .= $wpdb->prepare( " AND post_date > %s", date( 'Y-m-d', strtotime('-30 days') ) );

	return $where;
}

add_filter( 'posts_where', 'last_thirty_days' );

$some_posts = get_posts( array( 'suppress_filters' => false ) );

// Important to avoid modifying other queries
remove_filter( 'posts_where', 'last_thirty_days' );

?>

I Need GPL-Compatible Flash Video Player Suggestions

I am in the early stages on recoding my Viper’s Video Quicktags plugin from scratch and in the process I will be replacing JW Player with a free and open-source alternative. JW Player is really great, but sadly it’s released under a non-commercial license which just won’t do.

So please, if you know of any good Flash players that will do FLV, MP4, etc. please leave a comment with a link!

Here’s my list so far of players to compare and pick between: (I’ll update this list with suggestions)

  • Flowplayer (currently leaning towards this one, it seems really badass)
  • OS FLV

WordPress Code: Earlier Shortcodes

WordPress shortcodes run at priority 11 which is after wpautop(), wptexturize(), and other various default filters. While this can be desirable so that wpautop() doesn’t affect the output of the shortcode (the function is well known for not being perfect), it can also be a drawback as wptexturize() will malform your shortcode contents.

Take this shortcode usage for example:

This is some text.

[foobar]This is how you "quote" things.[/foobar]

This is some more text.

The “foobar” shortcode callback will receive the following string:

This is how you &#8220;quote&#8221; things.

Well that’s not obviously right. Okay, so you could fix it with some str_replace()‘es to reverse the fancy quotes and other changes, but why go to all the trouble?

Instead, let’s just make the shortcode run before priority 10 when wpautop(), wptexturize(), etc. mangle our shortcodes. That way we can process the shortcode as the user typed it and when once we’re done let wpautop() and it’s friends handle the content like they were designed to do.

First, here’s the code I use. I’ll explain it afterward.

// This will do nothing but will allow the shortcode to be stripped
add_shortcode( 'foobar', '__return_false' );

// Actual processing of the shortcode happens here
function foobar_run_shortcode( $content ) {
	global $shortcode_tags;

	// Backup current registered shortcodes and clear them all out
	$orig_shortcode_tags = $shortcode_tags;
	remove_all_shortcodes();

	add_shortcode( 'foobar', 'shortcode_foobar' );

	// Do the shortcode (only the one above is registered)
	$content = do_shortcode( $content );

	// Put the original shortcodes back
	$shortcode_tags = $orig_shortcode_tags;

	return $content;
}

add_filter( 'the_content', 'foobar_run_shortcode', 7 );

The function starts by global’ing the variable $shortcode_tags. This is the variable that contains a list of all registered shortcodes. We then make a copy of that variable (so we can restore it later) and then empty it out so that no shortcodes are registered.

Now that there’s no shortcodes registered, we register our shortcode and call do_shortcode() which is the function that replaces shortcodes with their contents. Once that’s done, we restore all of the previously registered shortcodes (this also unregisters our shortcode so it doesn’t run again) and return the result of the do_shortcode() call.

Lastly we register that function as a filter but at an earlier priority than wptexturize() so that it will run first. Any number between 1 and 9 will do — I just use 7 as it’s fairly late but still leaves room for other filters to come after it but before wptexturize(). That and it’s my favorite number. 😉

Questions? Improvements? Then leave a comment. 🙂

Breaking “Click-In That Captcha”

I ran across a tutorial about how to make a fairly clever CAPTCHA where solving it relies on clicking on a particular part of the image rather than filling in a field. While the concept itself is clever, the implementation given in the tutorial is not (requiring the user to click on a particular color). The problem with that is that computers are very good at knowing the colors of things too.

So just for fun (and to see if I could do it), I wrote a script that beats the CAPTCHA each and every time and in the process submits fake spam to the form it’s attempting to prevent (I know, I’m an evil dirty spammer ;)). If you’re interested, read their tutorial first and then check out the rest of this post for how to beat it.

Keep reading »

Adding New Default Gravatars To WordPress 2.6

Gravatar support was added into the WordPress core in 2.5. You could toggle them and chose what rating level (G/PG/PG13/R/X) you wanted to allow, but you couldn’t easily change the default avatar for users without a custom Gravatar. That is, until recently.

Earlier this month, Ryan committed a modified version of a patch I wrote. It adds a list of default avatars to the bottom of the discussion options page and has already been added to WordPress.com.

What does this mean for theme developers? Well, this new feature also allows you to define custom default avatars that better match your theme. Here is some example code that you would add to your theme’s functions.php:

&amp;amp;amp;amp;amp;lt;?php

add_filter( 'avatar_defaults', 'mytheme_addgravatar' );

function mytheme_addgravatar( $avatar_defaults ) {
	$myavatar = get_bloginfo('stylesheet_directory') . '/images/avatar.png';
	$avatar_defaults[$myavatar] = 'My Theme';
	return $avatar_defaults;
}

?&amp;amp;amp;amp;amp;gt;

That will add a new default avatar option to the bottom of the user’s settings page.