附件上传时自动分类

Lets say the media library has the following category [news, events, photo, page, post]

Your wordpress also has the above 5 set as post-type. What I want is when

1- Events -> Add New
2- File is uploaded while adding a new events post-type
3- File Finished uploading, wordpress should automatically attach events category for that attachment file.

I have code to update the category to a set value after upload, but could not find the currently editing post-type when running this function.

adds category 3 to the uploaded file

 function add_category_automatically($post_ID) {
            wp_set_object_terms($post_ID, array(3) or 'cat_slug_goes_here', 'category', true);
    }
    add_action('add_attachment', 'add_category_automatically');

gets currently editing post-type via ID (this displays correctly)

add_action( 'admin_init', 'do_something_152677' );
function do_something_152677() {
    // Global object containing current admin page
    global $pagenow;
    // If current page is post.php and post isset than query for its post type
    if ('post.php' === $pagenow && isset($_GET['post'])) {
        global $new_current_post_type;
        $new_current_post_type = get_post_type( $_GET['post'] );
    }
}

When pulling this value into cat_slug_goes_here the category does not get updated because the value doesn't match.

If the image is uploaded when creating the event using the "Add Media" function of the editor, then it should be associated with the original post by the time the action hook runs.

You can then:

function add_category_automatically($post_ID) {
    $attach = get_post($post_ID);
    if ($attach->post_parent) {
        $cats = get_the_category()($attach->post_parent);
        foreach ($cats as $cat) {
            wp_set_object_terms($post_ID, $cat->slug, 'category', true);
        }
    }
}
add_action('add_attachment', 'add_category_automatically');