1

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:

  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?

  • "When changing an attachment categories, if it has none, set it to "Uncategorized"" - can you elaborate this line a little bit ? – Shazzad Feb 22 '14 at 16:47
2

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 );
}

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.