Filter documents in WordPress media library

This post is more than 10 years old.

The WordPress media library has a few nice features for managing uploaded files. One thing it doesn’t do is make it easy to find documents. It makes it easy to filter all the files to list only the images, or video, or even audio files, but not documents like PDFs, Word documents, spreadsheets etc. But adding a Documents link to the media library is just a few lines of code away.

Those links across the top of the media library, for filtering on Images or Video or Audio, are based on the MIME types of the files loaded onto the server. There is an array that WordPress uses to specify which generic MIME types to show filters for, based on the first characters of the MIME type: “image” gets all the JPEG (image/jpeg), GIF (image/gif) and PNG (image/png) files for example. Here’s the array WordPress 3.2.1:

$post_mime_types = array(   //  array( adj, noun )
    'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
    'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
    'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),

Documents… well, most documents have a MIME type that starts with “application”, e.g.

  • PDF is application/pdf
  • Word documents can be application/msword or application/vnd.openxmlformats-officedocument.wordprocessingml.document
  • Excel spreadsheets can be application/ or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • OpenOffice documents are in the application/vnd.oasis.opendocument.* family

So adding a filter link for Documents means telling WordPress to look for files with a MIME type starting with “application”. OK, so it will pick up some other files like Flash and .ZIP, but at least it will cut out the forest of image and video files.

Luckily, there’s a filter hook that WordPress calls just after it creates that array, so that we can add to it ourselves. Here’s how to add that hook into your plugin:

* add custom "mime types" (file supertypes)
* @param array $post_mime_types
* @return array
function filterPostMimeTypes($post_mime_types) {
    $post_mime_types['application'] = array('Document', 'Manage Documents', _n_noop('Document <span class="count">(%s)</span>', 'Documents <span class="count">(%s)</span>'));
    return $post_mime_types;
add_filter('post_mime_types', 'filterPostMimeTypes');

And here’s the result:

There, job is done without having to fight through all those bloody images to find the PDFs!