Audit Post Attachments

One of the more annoying things about WordPress is the inability to see how many files are attached to a post without invoking the media upload area. Here’s a plugin I whipped up to report posts and their attachments by post type. Enjoy!

WordPress Remove Attachment Rows Where File Doesn’t Exist

Here’s a nifty script I cooked up tonight. This basically looks through all of your attachments and see if the associated real files exist on the server. If they don’t, the attachment database row is deleted. I realize this isn’t the most useful tool for everyday use. It was built for a one-off use case and I didn’t want this script to get dusty in my local files. So, here it is for your consumption or truncation!

Sublime Text WordPress Snippets and Auto-completions

I have become a huge fan of Sublime Text 2 as of late. It’s a simple, yet behemoth-featured editor that allows you to craft your own unique editing experiences. This post is not touting all the wonderful features about Sublime, but if you’re not using it you should be. It’s available for Mac, Windows and Linux.

I primarily develop websites based on WordPress, and I find myself frequenting the Codex on a daily basis to look up parameters that I haven’t memorized. Over time this can amount to a lot of time wasted. Fortunately for me and you, there is a Sublime WordPress package ready for you to install in mere seconds. This gives us a lot of WordPress goodness at our fingertips right in the editor.

To install through Package Manager, type CMD-SHFT-P (Macs) and ‘Type Package Control: Install Package’. Wait for the package search dialogue to appear then type ‘WordPress’ and hit enter. Boom. Done.

To take advantage of all the new WordPress goodness, simply type a WP-specific function and hit tab to auto-complete. Repeatedly hitting tab will move through the function parameters. There is also snippet goodness as well. You can take a look at all of the snippets and auto-completions here.

For instance if you would like to insert a plugin header, make sure you are in PHP syntax mode and type ‘plugin_head’ and then hit tab. In the CSS syntax mode, you can type ‘theme_head’ and move through all of the definitions with the tab key.

This is not even the tip of the tip of the tip of the iceberg with Sublime. Here’s a great course on what Sublime can do for you and your workflow.

If you would like to install the WordPress Sublime package manually, go to: https://github.com/purplefish32/sublime-text-2-wordpress and clone the repo to your package library.

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);