Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

<?php

// 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??

            return;
        }

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

        // if attachment has no categories, set default category
        wp_set_post_categories( $post_ID, array( get_option('default_category') ) );
    }
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Worked flawlessly. Thanks! Follow-up question: Do you think I should run the "remove" inside a loop? –  Dbugger Feb 22 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 Feb 22 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? –  Dbugger Feb 22 at 23:36
    
You will need the loop you already have. –  s_ha_dum Feb 22 at 23:40
    
It seems like I don't! this works quite well :) gist.github.com/enriquemorenotent/9164197 –  Dbugger Feb 22 at 23:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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