Categories – Filter wp_dropdown_categories per post type

I’m using wp_dropdown_categories to add category filters to a media library. This works fine, except that it displays all categories that are assigned to posts, but I want it to display only those categories that are assigned to attachments. It would also be nice if the count was updated only for attachments as well. Here is the code that adds categories to attachments and then allows you to filter them.

/* Add categories to attachments/media library */
function wptp_add_categories_to_attachments() {
register_taxonomy_for_object_type( 'category', 'attachment' );
add_action( 'init' , 'wptp_add_categories_to_attachments' );

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

If there was a post_type argument for wp_dropdown_categories that would be ideal. I knew I could create a custom taxonomy, but I’d like to know what the solution is without doing this.

Leave a Comment