Clear Terms from Taxonomy for Specific Post IDs?

Trying figure out how I can use some SQL/$wpdb->query to delete all the terms from a taxonomy that are related to specific post IDs. The following works beautifully to delete all the terms from a specific taxonomy, but I need to modify it to only remove ones associated with specific post IDs as mentioned.

// Clear Terms from Taxonomy 'post_tag'
DELETE t, tr, tt
FROM wp_terms t  
INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
INNER JOIN wp_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.taxonomy = 'post_tag'

I’m also using the following to delete posts (works great):

$wpdb->query( "DELETE FROM $wpdb->posts WHERE ID IN (".implode( ", ", $postIds ).")" );

I’ve tried to do the following but it doesn’t clear the associated terms they just remain as orphaned in the DB, it just clears the relationship.

// Delete Post Terms
$wpdb->query( "DELETE FROM wp_term_relationships WHERE object_id IN (".implode( ", ", $postIds ).")" );

I’m a novice when it comes to SQL, any help is appreciated, thanks in advance!

Go to Source
Author: contempoinc