Removing all post tags except a given list

Assuming you have a CSV file of your excluded ids and that this file name is exclude_tags.csv

the format of that file should be

1,2,3,4

This would represent tags with id 1,2,3 and 4

try this

$ wp term list post_tag --exclude=$(cat exclude_tags.csv) --field=term_id | xargs wp term delete post_tag

Basically, this will send the output of wp term list to xargs which will execute the wp term delete command

Get all Tags

This will generate a file all_tags.csv containing all your tags, you could use it to generate your excluded_tags.csv file

wp term list post_tag --format=csv >all_tags.csv

NOTE

I was trying to do it all on command line, but for some reason I can’t pass an array of term slugs to the wp function. I asked over on github, if I get a reply I’ll update it here. So the following would fetch all tags and provide a csv file containing only the tags id in --slug= that parameter would accept my array.

paste -sd, <(wp term list post_tag --field=term_id --slug=[tag1,tag2,etc]) >excluded_tags.csv

UPDATE

as it turns out, supplying multiple term slugs to --slug=<slugs> isn’t supported as per my github ticket, so you would need to generate an intermediate file and manually work with that to generate your excluded_tags.csv file before deleting your unwanted tags.