Add a category to media items in WordPress

If you want to add categories to images and/or other uploaded files in your WordPress media library (in versions 3.5 and above) it’s really easy — once you know how. First register the taxonomy (I’m just using the built in ‘category’ taxonomy type in WordPress, but you could be all fancy and add your own taxonomy if you really want to).

/** Register taxonomy for images */
function olab_register_taxonomy_for_images() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
add_action( 'init', 'olab_register_taxonomy_for_images' );

Now add the category field to the Media Library table. This will also add a filter to the table to allow search of attachments by category. Super useful if you’ve got a bunch of files you need to categorize.

 /** Add a category filter to images */
function olab_add_image_category_filter() {
    $screen = get_current_screen();
    if ( 'upload' == $screen->id ) {
        $dropdown_options = array( 'show_option_all' => __( 'View all categories', 'olab' ), 'hide_empty' => false, 'hierarchical' => true, 'orderby' => 'name', );
        wp_dropdown_categories( $dropdown_options );
add_action( 'restrict_manage_posts', 'olab_add_image_category_filter' );

Make sure to replace ‘olab’ with whatever prefix you’re using in your theme and/or plugin.

9 Replies to “Add a category to media items in WordPress”

  1. Richard, thanks a million for sharing this snippet – very helpful! I look forward to the day WP has a shortcode option taking advantage of the potential here. Cheers!

  2. Thanks a lot. I have one question, is it possible insert same filter into media uploader window (WP 3.5)?

  3. Hi Patrik, it’s really annoying but it doesn’t really seem to be possible to add another filter to the new uploader (I’d very happily be proved wrong!). The new uploader has essentially zero documentation :(

    There’s talk about adding action hooks and filters into JavaScript in WordPress, if that happens then this may be possible!

  4. Hi, it seems the images are not registered as posts under the respective categories? The category is saved alright, but if I browse the content of same category, it\’s still empty. Why is this, and how can I make it so that the images are represented as active posts in the category? Thanks for your time, great lines of code!

Comments are closed.