By now most people have figured out what is the difference between categories and tags, and which ones to use where. But that doesn’t necessarily mean that the problems are over. Once in a while there is a need to convert from one to another.
WordPress provides the tool to convert from categories to tags. But I needed something for the reverse process. In fact, I had a slightly more complicated situation – I already had both a tag and category with exactly the same name, and a whole lot of posts which were tagged, or categorized, or both. Messy! I was looking for a quick way to add all posts tagged with specific tag to the category with the same name. Once that is done, I could easily delete the tag. After a few Google searches, nothing straight-forward came up, so I decided to not waste anymore time and wrote my own little script.
Below are the pros and cons of my approach.
Pros:
- Standalone script, not a WordPress plugin. It is not utilizing any of the WordPress configuration or functionality, but raw PHP and direct connection to the database. You can do a dump of your database, restore it on a totally different machine and play with this script until you are sure you are getting the expected results. No worries about screwing up the live database.
- Requires both the tag and the category to be present. It will not proceed unless it will find both.
- Safe. While there is no undo for the effects of the script, it still works pretty safe. Nothing is ever deleted or updated in the database. Only the new records are added – for posts to appear under the selected category. Nothing else!
Cons:
- Standalone script, not a WordPress plugin. It is not utilizing any of the WordPress configuration or functionality. You will have to specify your database credentials by editing the script. You will also might need to change SQL queries to reflect your WordPress tables prefix.
- Runs from the command line. If you don’t have access to or don’t know how to use the command line – tough luck!
- Code quality. I wrote this as a very quick and dirty solution to my problem. It is not intended to be executed frequently. Neither it is not intended to be executed by someone other than myself. Yeah, I know, this will probably change, but I don’t care at this stage.
Now, you’ve been warned, so I won’t be holding you off from the source code any longer.
Continue reading Convert WordPress tag to existing category