sortable custom column in media library

You cannot do a sort on the attachment meta data specifically because it’s stored in a serialized string.

Whilst WP_Query can sort on meta values it can’t sort on data that’s serialized. For example wp_get_attachment_metadata fetches and unserializes that for you inside the column callback, but MySQL queries can’t sort on that type of data.

Short answer: Not possible due to how the width and height are stored.


Follow-up:

Of course, if you setup the image height or width as seperate meta values you can then query on that, or should be able to at least, using a couple more hook(in addition to what you have).. manage_upload_sortable_columns and request.

// These would go inside your admin_init hook
add_filter( 'manage_upload_sortable_columns', 'isv_column_register_sortable' );
add_filter( 'request', 'isv_column_orderby' );

function isv_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'Width' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => '_im_width',
            'orderby' => 'meta_value_num'
        ) );
    }
    return $vars;
}
function isv_column_register_sortable( $columns ) {
    $columns['isv_width'] = 'Width';
    return $columns;
}

If it helps more, Scribu gave an example of creating new sortable columns here. Note, the hook for the media listing is upload and not media for the sortable columns(because the hook is the screen id).

I tested this alongside your code and it did work, minus the sort order being off, because i don’t have the _im_width key associated with media in my install.

I hope that’s enough info to work from, and be sure to check the link to Scribu’s page if you want to see a more complete example of sortable columns.

Leave a Comment