function add_taxonomy($attachments, $taxonomies) { foreach ($attachments as $id) { foreach ($taxonomies as $taxonomy => $terms) { if (!taxonomy_exists($taxonomy)) { continue; } wp_set_object_terms($id, $terms, $taxonomy); } } }