0

I'm using wp_dropdown_categories to add a categories filter to the media library. It works fine, except it displays all the categories that are assigned to posts, but I would like it to only display categories that are assigned to attachments. It would also be nice if the count was updated for attachments only 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 known I could create a custom taxonomy, but I'd like to know what the solution is without having to do that.

0

"Category" is a taxonomy. What you're looking to do is limit the number of "terms"

Depending on your goal (I think you want to show comingled attachments and posts in one giant list/interface?) - what you could do is create a new taxonomy, call my_attachment_terms and then add terms to that taxonomy and label them appropriately, **utilize the wp_insert_term ** function - specifically marking it as an alias of an existing term.

https://codex.wordpress.org/Function_Reference/wp_insert_term

'alias_of' (string) (optional) There is no default, but if added, expected is the slug that the term will be an alias of. Default: None

I'm not sure what the implications of using this on the OOTB category taxonomy is, so I would recommend working with custom taxonomies first, if you do not have a dev environment that you can wipe and reset at a whim

good luck!

  • Yes, I'm looking to limit the category terms that are associated with attachments only. I'm not quite sure why I'd want to show commingled attachments and posts together? Seems like that would be another discussion. – eleclair May 26 '15 at 19:28
  • I made the assumption because otherwise, having the common taxonomy only creates these issues you're facing. Terms are unique to taxonomies, in terms of slugs and labels. If you do not need some easy-button to comingle posts, pages, attachments, etc... then a separate taxonomy makes the most sense. – Brandt Solovij May 26 '15 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.