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.

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!

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

WordPress enforces CamelCase

As of WordPress 3.0, you cannot type WordPress incorrectly in your titles or content. A patch was introduced to filter out any bad formatting of the WordPress name and replace it with the proper CamelCase format. Notice the following screenshot of my content area which includes several mis-formattings of WordPress that are formatted automatically.

So, patch author, Matt Mullenweg, wants to set the record straight that WordPress is spelled with a capital P. I guess the motivation of this is for brand integrity, however, this has caused quite a ruckus among the orthodox GPL folks. We won’t go into that on this post. If you wish to continue misspelling WordPress, you can add this to your functions file.

remove_filter('the_content', 'capital_P_dangit', 12);
remove_filter('the_title', 'capital_P_dangit', 12);
remove_filter('comment_text', 'capital_P_dangit', 12);

Find a widget’s current sidebar context

I recently was programming a widget for WordPress that needed to communicate with another widget if it was at a lower priority in the same sidebar. I came up with these nifty little functions to find the current context and sibling widgets of the current widget. You can add this to your functions.php.

function get_current_sidebar($widget_id) {

    $active_sidebars = wp_get_sidebars_widgets();
    $current_sidebar = false;
    
    foreach($active_sidebars as $key => $sidebar)
        if(array_search($widget_id, $sidebar))
            $current_sidebar = $key;    
    
    return $current_sidebar;
}

function get_current_sidebar_widgets($sidebar_id){

    $active_sidebars = wp_get_sidebars_widgets();
    $current_sidebar_widgets = $active_sidebars[$sidebar_id];

    return $current_sidebar_widgets;
}

Add this method to your widget object:

protected function has_widget_siblings(){

    $widget_id = $this->id_base.'-'.$this->number;
    $current_sidebar = get_current_sidebar($widget_id);
    $current_sidebar_widgets = get_current_sidebar_widgets($current_sidebar);
    
    $current_widget_identified = false;
    $current_widget_siblings = false;
    
    foreach($current_sidebar_widgets as $key => $widget){
        if(preg_match("/{$widget_id}/", $widget)){
            $current_widget_identified = true;
        }
        elseif(preg_match("/{$this->id_base}/", $widget)){
            if($current_widget_identified)
                $current_widget_siblings = true;
                return $current_widget_siblings;
        }
    }
}

Read my post about passing data between classes to have your widget communicate with a sibling widget.