I have enabled categories on attachments, and I am trying to implement the logic to automatically handle the "Uncategorized" category, like this:

1) If the attachment has no categories, set it to "Uncategorized"

2) If the attachment has some category besides "Uncategorized", remove "Uncategorized" from the post's category list

I have tackled most of the logic, except that now I dont know how to remove the category from the Attachment. This is my code:


// Enable categories with attachments
register_taxonomy_for_object_type( 'category', 'attachment' );

if( is_admin() ) {

    add_action('add_attachment', 'emt_set_attachment_category');
    add_action('edit_attachment', 'emt_set_attachment_category');
    function emt_set_attachment_category( $post_ID ) {

        $attachmentCategories =  wp_get_object_terms( $post_ID, 'category' );

        // if attachment has many categories, remove the default category
        if (count($attachmentCategories) > 1) {
            foreach ($attachmentCategories as $key => $category)
                if ($category->name == "Uncategorized")
                    // How to delete it??


        // if attachment already have categories, stop here
        if (count($attachmentCategories) == 1)

        // if attachment has no categories, set default category
        wp_set_post_categories( $post_ID, array( get_option('default_category') ) );

1 Answer 1


You want wp_remove_object_terms().

if ($category->name == "Uncategorized") {
    wp_remove_object_terms( $post_ID, 'uncategorized', 'category' );

Untested but "Attachments" are pretty much just posts under the hood, so I am fairly sure that should work.

  • Worked flawlessly. Thanks! Follow-up question: Do you think I should run the "remove" inside a loop? Commented Feb 22, 2014 at 23:27
  • I am not sure I understand. Why would you need a loop? You are only removing a single category.
    – s_ha_dum
    Commented Feb 22, 2014 at 23:29
  • Oh, I see. You mean that I don't need the loop that I posted in the question? If I try to remove the category "uncategorized", but the attachment isnt set to that category, no error will be given? Commented Feb 22, 2014 at 23:36
  • You will need the loop you already have.
    – s_ha_dum
    Commented Feb 22, 2014 at 23:40
  • It seems like I don't! this works quite well :) gist.github.com/enriquemorenotent/9164197 Commented Feb 22, 2014 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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