FileMerge Fail – Changes App Awesome

So, I’ve been using the de facto FileMerge religiously for the past couple of years. With the latest OS iteration, FileMerge has failed miserably using 10.8.1. Basically, FileMerge would not allow you to save a file after an hour of intricate merging. This is an equation for higher blood pressure. Apparently OS 10.8.2 fixes this issue now, but it was not available during my period of serious frustration, so I began to look elsewhere.

I tried the Kaleidoscope app, but was disappointed as it only compares files, but has no merge capabilities. Albeit, a beautiful application, but useless to me nonetheless without merging. It’s price is $39.00 which is pretty steep for just comparing files.

After a bit of searching, I stumbled upon the Changes app. It’s certainly not as fancy as the previously mentioned app, but it does everything I need it to do. The feature I’ve found most useful is the “Copy To Left” and “Copy To Right” feature. This does inline merging. That means no waiting for post processing an entire file, your changes are saved instantaneously.

It’s a bit of an investment at $40.00 USD ($1 more than Kaleidoscope – spend the extra dollar), but it’s well worth the time and frustration saved. There are many other features that I don’t even use that might be useful to you as well.

Arrrrrrr, clean up your whitespace matey

I get thoroughly annoyed at code files littered with EOL and BOL tabs and spaces. Here’s a simple regex I use to garbage collect rogue whitespace. Just use find/replace and set your search to regex within your IDE. Replace with null.

[ \t]+$

WordPress Hooks and jQuery Custom Events

WordPress Hooks

If you develop with WordPress, you’re very familiar with the Plugins API. This allows you to ‘hook’ into most any part of the application and either filter data or run bits of code at a desired sequence point.

A sample action hook might look like this:

add_action('init', 'foobar_register_post_type', 0);
function foobar_register_post_type(){
    //Do something
}

A sample filter hook might look like this:

add_filter('query_vars', 'foobar_add_public_query_var', 0, 1);
function foobar_add_public_query_var($vars){
    $vars[] = 'foobar_var';
    return $vars;
}

There are hundreds of way to extend WordPress which is why it’s an amazing application upon which to develop. You can even create your own custom hooks using something like the following:

do_action('foobar_action');
$data = apply_filters('foobar_filter', $data);

This gives others access to extend your code with a couple lines of code in the right spots.

jQuery Custom Events

Many WordPress developers are building nice front-end experiences these days on jQuery (JavaScript). More specifically, plugins and themes are using AJAX instead of using native $_POST or $_GET behavior. The problem I’ve run into with several plugins is their lack of front-end extensibility.

On the server-side, the proper WordPress hooks usually exist, but there’s typically no way to extend specific events on the client-side. jQuery gives us the ability to easily follow the pattern of WordPress hooks.

A simple custom event might like this:

//This is similar to the WP function add_action();
jQuery(document).bind('foobar_custom_event', function(event, param1, param2){
    //Do something
});

The way to trigger a custom event is as follows:

//This is similar to the WP function do_action();
jQuery(document).trigger('foobar_custom_event', {arg1 : ['foo', 'bar', 'hello', 'world'], arg2 : 'Hello World' });

As you can see we trigger ‘foobar_custom_event’ and pass in arguments to the callback. If you build plugins or themes for WordPress, it’s as simple as that to make your client-side scripts as extensible as your server-side scripts.

An example use-case would be to allow other plugins to hook into a form submission success state to pass the submitted data onto a third-party API or post it their own registered ‘wp_ajax’ hooks.

There’s no need for building out a complex hook system in JavaScript. It’s already available to you. It’s up to you to make your application as open as possible to cultivate creativity around your codebase.

Create an API Endpoint in WordPress

If you’re looking to setup a nice URI structure for an API endpoint within WordPress, there are a few approaches to accomplish this.

Approaches

1. Add a literal directory to your docroot and load WordPress outside of a typical index request with wp-load.php. This can cause some headaches and you have code residing outside of WordPress to maintain.

2. Create a page and assign an API endpoint page template. This is not too desirable as other editors/admins can easily touch this page.

3. Create an endpoint with a rewrite rule.

Example

I created an example API endpoint to serve up pug bombs from the ever awesome Pug Bomb API. You can download the fully functional API endpoint plugin here. Here’s the code:

Once you activate the plugin, you will need to visit the Permalinks page to flush the rewrite rules.

Overview

Here’s a brief overview of how this works:

– A rewrite rule is added for /api/pugs/{N_PUGS} and passes a hidden query var __api and number of pugs.

– An api request sniffer watches for the query variable __api and sends the request to be processed and subsequently kills the rest of the WordPress processes.

– The pug bomb request is validated and processed a JSON response is sent to the browser with an error or pug bomb goodness.

Feel free to ping me if you have any questions. Enjoy the script and hug a pug!

Accept only specified arguments in a function or class method

There are times that I’ve needed to limit input into a class method or function while using the extract() function. Problems arise at times from rogue argument keys that aren’t necessarily needed. Here’s a simple way to use the awesomeness of extract(), but dictate its output to the parameters of your allowed vars.


$allowed_vars('foo', 'bar', 'foobar'); 

# Set allowed vars as $ variables
extract($allowed_vars);

# Extract only allowed vars from user-submitted arguments
# EXTR_IF_EXISTS will only convert array keys of foo, bar, and foobar
extract($args, EXTR_IF_EXISTS);

Deprecation Checker – WordPress Plugin

Inspired by this question on WPSE, I decided to create a plugin that scanned defined directories for deprecated functions.

Deprecation Checker collates a list of deprecated functions directly from the installed WordPress core files. By default, the themes and plugins directories are scanned automatically. I’ve included a couple hooks for developers to extend the plugin for their own uses by adding custom paths to scan (recursively) and custom deprecated functions to look for.

Once you install the plugin, simply browse to the Tools administration menu and start scanning your files. It might amaze you how many of your installed plugins and themes are out-of=date!

Download the Deprecation Checker Plugin

Plugin Promoter – WordPress Plugin

I created Plugin Promoter to help plugin developers get the word out about their awesome plugins released at WordPress.org.

Here’s what’s baked in:

* A nifty plugin badge widget that gives you a download count and download link
* A shortcode to display the details of your plugin right from WordPress.org (Similar to what you see on wp-admin when searching for a plugin)

Example Badge

Plugin Promoter

WordPress Plugin1KDownloadsDownload Now »

Screenshots

Download Plugin Promoter

Kint Debugger for WordPress

We just released a new UpThemes plugin called Kint Debugger for WordPress. It’s a simple wrapper for the awesome Kint debugger class. It allows you to view variable dumps in a styled and collapsible output. Kint also allows for easy back-tracing.

Examples

global $wp_query;
d($wp_query); //styled, collapsible output
s($wp_query); //un-styled output

I added a couple WordPress specific functions to aid in plugin and theme development.

dump_wp_query();
dump_wp();
dump_post();

View the entire documentation at the Kint site.

Check out the UpThemes plugin page.

Download Kint for WordPress

Create your own admin-ajax.php type handler

The admin-ajax.php handler is a bit heavy, especially if you’re using AJAX on every page load. I am working on a project now that has multiple caching mechanisms and the only way to update the original server is to POST to the server. Since admin-ajax.php invokes the admin_init hook, it loads a lot of unnecessary items for AJAX call. Here’s the light-weight version of admin-ajax that I created to handle my plugin’s AJAX calls. Save this as request.php in your plugin folder.

define('DOING_AJAX', true);

if (!isset( $_POST['action']))
    die('-1');

//relative to where your plugin is located
require_once('../../../../../wp-load.php'); 

//Typical headers
header('Content-Type: text/html');
send_nosniff_header();

//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');

$action = esc_attr($_POST['action']);

//A bit of security
$allowed_actions = array(
    'action_1',
    'action_2',
    'action_3'
);

if(in_array($action, $allowed_actions)){
    if(is_user_logged_in())
        do_action('plugin_name_ajax_'.$action);
    else    
        do_action('plugin_name_ajax_nopriv_'.$action);
}
else{
    die('-1');
}

To use this you obviously would hook into these actions doing the following:

//For logged in users
add_action('plugin_name_ajax_action_name', 'function_callback_name');

//For logged out users
add_action('plugin_name_ajax_nopriv_action_name', 'function_callback_name');

You will need to craft your AJAX request as follows:

jQuery(document).ready(function($){
    var data={
         action:'action_name',
         otherVar: varValue
    };
    $.post('http://url/to/your/plugin/request.php', data, function(response){
         alert(response);    
    });
});