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):

// Delete Posts 
$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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

So if you’re sure you want to delete the actual term as well as the relationship that assigns the term to the post, this will do it (tested and works for me):

delete term from wpterm_taxonomy term, wpterm_relationships rel 
where  term.term_taxonomy_id = rel.term_taxonomy_id and rel.object_id IN (1) ;

And obviously replace the ‘1’ there with how you’re selecting the post ID’s

I would strongly recommend you test this before running it with e.g. this query which will show which terms will be deleted before you do it! And take a database backup before you’re doing large deletes in case something goes wrong 😉

select term.term_taxonomy_id from wpterm_taxonomy term, wpterm_relationships rel 
where  term.term_taxonomy_id = rel.term_taxonomy_id and rel.object_id IN (1) ;

Again replace ‘1’ with however you create your list of post ID’s


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x