We’ll bulk add a tag to all posts in a category as a simple use case. But this approach can be modified to handle other use cases also.
- First find the term_taxonomy_id for the term you want to add. Lets assume its value is 183 for the purpose of this tutorial.
-
Now run the following query to take a backup of wp_term_relationships
create table wp_term_relationships_bak AS select * from wp_term_relationships;
-
We’ll use the following query template (assuming post_id value is 7931) to insert a tag in wp_term_relationships for a post.
INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES (7931, 183);
-
To bulk update all posts matching our criteria (e.g. all posts belonging to term_taxonomy_id 84) construct a query which returns post_id and term_taxonomy_id we want to insert (183 in our case) as shown below:
select wp_posts.ID, 183 from wp_posts join wp_term_relationships on (wp_posts.ID = wp_term_relationships.object_id) where wp_term_relationships.term_taxonomy_id = 84;
-
Run to following query to insert the new tag for all the posts as returned by above query. Note that insert will fail if there is a duplicate.
INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) select wp_posts.ID, 183 from wp_posts join wp_term_relationships on (wp_posts.ID = wp_term_relationships.object_id) where wp_term_relationships.term_taxonomy_id = 84;
- In addition you may have to update plugins which maintains cache based in tag name. One such plugin is Yes Another Related Posts Plugin (YARPP). You can look at this thread for updating YARPP cache.