Sublime 2: Open New Tabs On The Right

One of the few things that bugged me about my favorite text editor, Sublime 2, is that new tabs would open up next to the current tab instead on the far right. Since I usually have about a half-dozen tabs open at once, this made keeping them in a sane order frustrating.

Thankfully Stylishmedia has written a simple little Sublime 2 plugin that makes new tabs open on the right side. Perfect. 🙂

Using Traits In PHP 5.4

I just read a great article by Shameer C. about traits in PHP 5.4. I’m really looking forward to using this functionality. Basically you can create things called traits, modules if you will, that you can then include into classes that you are writing.

For example if you need to deal with the filesystem, you could load in a filesystem trait that provides you with pre-written functionality. Or if you needed to make remote requests, you could load in a HTTP trait. Classes can only extend a single other class but you can use as many traits as you want.

This will be so useful!

Thanks Mo for sending me the link!

How To Create Custom WordPress Cron Intervals

This is mostly a reminder for myself so I can stop tracking it down every time I forget, but here’s how to have WordPress code execute on a different schedule than the default intervals of hourly, twicedaily, and daily. This specific example is for weekly execution.

[code lang=”php”]<?php

// Add a new interval of a week
// See http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules
add_filter( ‘cron_schedules’, ‘myprefix_add_weekly_cron_schedule’ );
function myprefix_add_weekly_cron_schedule( $schedules ) {
$schedules[‘weekly’] = array(
‘interval’ => 604800, // 1 week in seconds
‘display’ => __( ‘Once Weekly’ ),
);

return $schedules;
}

// Schedule an action if it’s not already scheduled
if ( ! wp_next_scheduled( ‘myprefix_my_cron_action’ ) ) {
wp_schedule_event( time(), ‘weekly’, ‘myprefix_my_cron_action’ );
}

// Hook into that action that’ll fire weekly
add_action( ‘myprefix_my_cron_action’, ‘myprefix_function_to_run’ );
function myprefix_function_to_run() {
// Add some code here
}

?>[/code]

On a side note, I believe this must go in a plugin and not your theme’s functions.php which I hear loads too late.

Code Snippet: Generate A Plaintext Data Table

Inspired by some awesome-as-always code written by my co-worker Mike Adams, here’s a helper function to help create plaintext data tables in PHP. This is particularly useful for PHP-based CLI scripts (we use quite a few at Automattic) or for plaintext e-mails.

But first, here’s an example output with the optional dividers enabled:

   ID | First Name     | Last Name   
-------------------------------------
    1 | Alex           | Mills       
    2 | John           | Smith       
    3 | Barack         | Obama       
    4 | Fred           | Flinstone   
12345 | ReallyLongName | IsReallyLong

Click here to keep reading and see the code »

Code Snippet: Helper Class To Add Custom Taxonomy To Post Permalinks

Say you have a custom taxonomy called “sport” and you wanted to inject “football” into the permalink of posts that have the “football” term assigned to it. How would you go about doing that? Well below is a helper class that will make it easy to accomplish exactly that.

Click here to read the rest of the post and see the code »

Code Snippet: Add A Link To Latest Post To WordPress Nav Menu

Someone on #wordpress IRC support channel was trying to add link to their latest blog post to their WordPress navigation menu, so I threw together a few lines of code to help them accomplish this.

[code language=”php”]// Front end only, don’t hack on the settings page
if ( ! is_admin() ) {
// Hook in early to modify the menu
// This is before the CSS "selected" classes are calculated
add_filter( ‘wp_get_nav_menu_items’, ‘replace_placeholder_nav_menu_item_with_latest_post’, 10, 3 );
}

// Replaces a custom URL placeholder with the URL to the latest post
function replace_placeholder_nav_menu_item_with_latest_post( $items, $menu, $args ) {

// Loop through the menu items looking for placeholder(s)
foreach ( $items as $item ) {

// Is this the placeholder we’re looking for?
if ( ‘#latestpost’ != $item->url )
continue;

// Get the latest post
$latestpost = get_posts( array(
‘numberposts’ => 1,
) );

if ( empty( $latestpost ) )
continue;

// Replace the placeholder with the real URL
$item->url = get_permalink( $latestpost[0]->ID );
}

// Return the modified (or maybe unmodified) menu items array
return $items;
}[/code]

Place the above code in a plugin or just in your theme’s functions.php file.

Create a new “Custom Link” menu item where the URL is #latestpost (which will act as a placeholder and target for the code). You can title the item whatever you please. This code will then find that menu item (by looking for the placeholder URL) and then replace it’s URL with that of the latest post’s URL. Since the filter is before the code that adds the selected CSS classes runs, the menu highlighting will even work. When you visit the latest post on your blog, this menu item will light up.

Rather simple and elegant. You gotta love WordPress hooks.

Changing Core WordPress Strings

One of the lesser known filters in WordPress is gettext. All strings that are run through the WordPress translation functions are also run through this filter after being translated thanks to a ticket I opened way back in 2008. That means you can actually use it to change pretty much any string in WordPress, namely in the admin area.

I’ve used this in some plugins I’ve written in the past and it works incredibly well.

My co-worker and one of the lead developers of WordPress Peter Westwood (westi) wrote a really good blog post about this, however I wasn’t completely happy with his code so I’m writing this blog post to share how I would write some code to take advantage of this versatile filter. Don’t get me wrong — he wrote good and valid code, but it’s not exactly the easiest thing for a novice to extend for their own uses.

[code lang=”php”]function youruniqueprefix_filter_gettext( $translated, $original, $domain ) {

// This is an array of original strings
// and what they should be replaced with
$strings = array(
‘View all posts filed under %s’ => ‘See all articles filed under %s’,
‘Howdy, %1$s’ => ‘Greetings, %1$s!’,
// Add some more strings here
);

// See if the current string is in the $strings array
// If so, replace it’s translation
if ( isset( $strings[$original] ) ) {
// This accomplishes the same thing as __()
// but without running it through the filter again
$translations = &get_translations_for_domain( $domain );
$translated = $translations->translate( $strings[$original] );
}

return $translated;
}

add_filter( ‘gettext’, ‘youruniqueprefix_filter_gettext’, 10, 3 );[/code]

So as you can see at it’s core it accomplishes the same thing as Peter’s code however my code should be a bit more clear on how to make it translate multiple strings.

Hope someone finds this helpful! 🙂

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

[php]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!’;[/php]

Reading Material:

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