Adding Category/Tag/Taxonomy Support to Images/Media

The question:

I’ve been trying to add category, tag, or custom taxonomy support to images (or all media, though I’m only concerned with Images). I’ve got it part-way figured out with:

add_action('init', 'create_image_taxonomies');

function create_image_taxonomies() {
$labels = array(
    'name' => 'Media Category'
);

$args = array(
    'labels' => $labels,
    'public' => true
);

register_taxonomy('imagetype', 'attachment', $args);
}

This properly adds a Media Category field to the media screen. I’ve also confirmed this can be accessed with get_the_terms($my_attachment_id, 'imagetype').

Where I’m running into trouble is getting this information to show anywhere in the admin/dashboard except when viewing the media directly — I want it either in a sub-menu or as a custom column, or both, as can be done for Posts and Pages.

I’ve tried using manage_posts_custom_column along with manage_edit-attachment_columns, but nothing at all is showing up. I’ve tried to use add_media_page to display something like the page automatically generated for Page and Post categories, but here I’m having trouble pulling the images to which I’ve given categories. You can see both attempts here: http://pastebin.com/S8KYTKRM

Thanks in advance for any assistance!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Here’s how I recently added a custom taxonomy to the media library as a sortable column:

// Add a new column
add_filter('manage_media_columns', 'add_topic_column');
function add_topic_column($posts_columns) {
    $posts_columns['att_topic'] = _x('Topic', 'column name');
    return $posts_columns;
}

// Register the column as sortable
function topic_column_register_sortable( $columns ) {
    $columns['att_topic'] = 'att_topic';
    return $columns;
}
add_filter( 'manage_upload_sortable_columns', 'topic_column_register_sortable' );

add_action('manage_media_custom_column', 'manage_attachment_topic_column', 10, 2);
function manage_attachment_topic_column($column_name, $id) {
    switch($column_name) {
    case 'att_topic':
        $tagparent = "upload.php?";
        $tags = wp_get_object_terms( $id, 'taxonomy_name', '' );
        if ( !empty( $tags ) ) {
            $out = array();
            foreach ( $tags as $c )
                $out[] = "<a href='".$tagparent."tag=$c->slug'> " . esc_html(sanitize_term_field('name'
                         , $c->name, $c->term_id, 'post_tag', 'display')) . "</a>";
            echo join( ', ', $out );
        } else {
            _e('No Topics');
        }
        break;
    default:
        break;
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment