Quickly change the post type or taxonomy with SQL
It gives me special satisfaction when a task that people solve with a plugin can be done faster than it takes to download and activate that plugin.
Problem: How to quickly change the post type or the taxonomy (for example, category) of many posts at once?
Solution: One SQL query in phpMyAdmin or the MySQL console. Make a backup of the database first: an UPDATE has no undo. The table prefix in the examples is wp_, use yours.
1. Change the post type
Change the post type post to the custom post type issue:
UPDATE wp_posts SET post_type = 'issue' WHERE post_type = 'post';
Only the posts of one category:
UPDATE wp_posts p JOIN wp_term_relationships tr ON tr.object_id = p.ID JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'category' JOIN wp_terms t ON t.term_id = tt.term_id SET p.post_type = 'issue' WHERE p.post_type = 'post' AND t.slug = 'my-category';
The post type issue must be registered in the theme or a plugin, otherwise the posts disappear from the admin (they are still in the database).
2. Change the taxonomy
Change the taxonomy category to issues_category, with all its terms and their relations to posts:
UPDATE wp_term_taxonomy SET taxonomy = 'issues_category' WHERE taxonomy = 'category';
Note that this also moves the default category “Uncategorized”. WordPress needs a default category for posts, so it is better to keep it out of the change:
UPDATE wp_term_taxonomy SET taxonomy = 'issues_category' WHERE taxonomy = 'category' AND term_id <> ( SELECT option_value FROM wp_options WHERE option_name = 'default_category' );
After the queries
- If the site has a persistent object cache (Redis, Memcached), flush it, otherwise WordPress will show the old data for a while.
- The term counters are not recalculated by SQL. They update when a post of the term is saved, or you can recalculate them by opening and saving the terms, for example with a bulk action.
- If the URLs changed, go to Settings → Permalinks and click Save Changes.
NOTE: Before the UPDATE, run a SELECT COUNT(*) with the same WHERE to see how many rows will change.