Speed up WordPress post list screens

IMG_1080

As I normally set a pretty high limit for posts (999) on the admin UI list table screens, the querying can get quite slow. After I did some testing, I saw that WordPress is calling every single field from the posts list table – even if it doesn’t need it. So I wrote a small (mu-)plugin, that reduces the queried fields. In a quick test, I could speed up the query by 50%. The plugin can as well be found on GitHub as Gist.

<?php defined( 'ABSPATH' ) OR exit;
/**
 * Plugin Name: (WCM) Faster Admin Post Lists
 * Description: Reduces the queried fields for admin post lists.
 * Author:      Franz Josef Kaiser
 * Author URl:  http://unserkaiser.com
 * Plugin URl:  https://gist.github.com/franz-josef-kaiser/5917688
 * License:     MIT
 * Version:     2013-07-03.1508
 */

add_filter( 'posts_fields', 'wcm_limit_post_fields' );
function wcm_limit_post_fields( $fields, $query )
{
    if (
        ! is_admin()
        OR ! $query->is_main_query()
        OR ( defined( 'DOING_AJAX' ) AND DOING_AJAX )
        OR ( defined( 'DOING_CRON' ) AND DOING_CRON )
    )
        return $fields;

    $p = $GLOBALS['wpdb']->posts;
    return implode( ",", array(
        "{$p}.ID",
        "{$p}.post_title",
        "{$p}.post_date",
        "{$p}.post_author",
        "{$p}.post_name",
        "{$p}.comment_status",
        "{$p}.ping_status",
        "{$p}.post_password",
    ) );
}

Update

As Stephen Harris pointed out in loopchat, there’s an even easier way using the posts_fields-filter. This filter runs earlier and now later plugins can modify the clause much safer. He also mentioned that there should be some more checks where to abort. Updated with Stephens notes. Thanks, Stephen, for the help.