Programmatically bulk removing an erroneous WP category

If you have a number of posts that have been wrongly assigned to a category, it’s easy enough to use the bulk add feature in the WordPress admin to add a NEW category but can be tricky to remove the erroneous category you no longer want.

WordPress lets you programmatically set categories from an array with “wp_set_post_categories” but to remove you first need to remove the offending category. To do this, I wrote a little function that loops through the categories and skips over the one you don’t want (id # 307 in this example but this is where you’d add the id of the category you want to remove if reusing) to rebuild a “clean” array:

Then just pass this clean array to the wp_set_post_categories function with the post id and you’re good to go.