Set the default category of an attachment

I wanted to apply the same categories that exist for posts to attachments, so I wrote this code:

function wpmediacategory_init() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init', 'wpmediacategory_init' );

The problem I am having now is that behaviour is not quite like with posts. There a 2 features I would like to achieve:

Read More
  1. When adding a new attachment, set it to “Uncategorized”
  2. When updating an attachment, if it has no categories selected, set it to the “Uncategorized” category.

I have been trying to think what hooks I could be using, but without much success. How could I solve this problem?

Related posts

1 comment

  1. To solve the problem 1, you could hook to add_attachment and edit_attachment hook.

    add_action('add_attachment', 'wpse_set_attachment_category');
    add_action('edit_attachment', 'wpse_set_attachment_category');
    function wpse_set_attachment_category( $post_ID )
    {
        // if attachment already have categories, stop here
        if( wp_get_object_terms( $post_ID, 'category' ) )
            return;
    
        // no, then get the default one
        $post_category = array( get_option('default_category') );
    
        // then set category if default category is set on writting page
        if( $post_category )
            wp_set_post_categories( $post_ID, $post_category );
    }
    

Comments are closed.