Turning WordPress Categories Into Tags «

Code: , , , ,
Comments Off on Turning WordPress Categories Into Tags

I recently updated this WordPress install from 2.2.something to 2.5 and noticed that it now supports tags instead of just categories. I had been using categories as tags, but I’d rather built-in tags than fake it anymore. I didn’t want to manually retag a couple hundred posts with ~200 tags, so I wrote some SQL to do it for me. If you’re in the same boat

Warning: This could break and completely mess up your categories and tags. I’m only promising this worked for me on my install for now (who knows, maybe I updated things wrong and huge problems will occur a month from now). Use caution. I take no responsibility.

# create tags for every category
insert into wp_term_taxonomy (term_id, taxonomy)
select term_id, "post_tag"
from wp_term_taxonomy
where taxonomy = 'category';

# copy category-post relationships to tag-post relationships
insert into wp_term_relationships (object_id, term_taxonomy_id)
(select i.term_taxonomy_id
from wp_term_taxonomy i
taxonomy = 'post_tag' and
i.term_id = wp_term_taxonomy.term_id)
from wp_term_relationships
join wp_term_taxonomy on
wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
where taxonomy = 'category';

# update tag count cache
update wp_term_taxonomy
set count = (select count(*)
from wp_term_relationships
where wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id);

# remove all categories and category-post relationships
delete from wp_term_taxonomy where taxonomy = 'category';
delete from wp_term_relationships
where term_taxonomy_id not in (select term_taxonomy_id from wp_term_taxonomy);

The INSERT INTO ... SELECT was a fun little query to write with its subselect. After running this, I just had to create and apply categories to my posts (I’m going with Biz, Code, Games, and Life for now) and update my templates.