Can I add a Category Metabox to attachment?

Edit: 12/09/2017
See this answer for a more up to date solution to this:
How to use taxonomies on attachments with the new Media Library?

I’m going to answer my own question here as I have managed to figure out a solution to what I’ve been trying to do. I came to the conclusion that it wasn’t possible to get the Category Metabox enabled for attachments. However, I found that it was easy enough to get a basic field for Categories added to the attachments page by using register_taxonomy_for_object_type and add_post_type_support:

add_action('admin_init', 'reg_tax');
function reg_tax() {
   register_taxonomy_for_object_type('category', 'attachment');
   add_post_type_support('attachment', 'category');
}

The field added showed like this:

alt text

It’s just a plain text field but what I found was that you could type the name of an existing category in there and it would then be successfully saved when the attachment was updated (The only odd behaviour is that it rendered back the normal version instead of the slug after saving).

Once I realised that I could save categories this way then I figured that I could get a list of all available categories as checkboxes and check the ones that had been selected. I then used a bit of jQuery to grab the values of checked categories and put all the categories’ slugs into the Category field. To make this seem even more seamless I then used a simple bit of CSS to hide the table row that contained the Category field, so all you ever see are the checkboxes, like so:

alt text

Now that I can add categories to image attachments I can use something like:

get_posts('post_type=attachment&category_name=timber-fixed-windows')

And pull the categorised images into a page! Exactly what I was hoping to do, I didn’t think there was going to be a way to do it but glad I managed to figure something out.

I’ve turned this into a plugin called WOS Media Categories which I have made available to download from my website, Suburbia.org.uk, I hope it may be of use to somebody else! Thanks again to those who commented on this and other questions I’ve asked here which helped figure it out!

Update: I’ve added a fix to enable categories to be added whilst images are uploaded using the Flash bulk uploader.

Leave a Comment