I have a WordPress site with hundreds of posts that have the category 'Uncategorized'. What I need to do is take these 'Uncategorized' posts and assign them to a category by the year they were created. That is, if a post was created in 2010 it should be assigned to category '2010'.
This is a bit beyond my SQL experience. This code will return a list of all the posts dated 2010.
select p.id, p.post_title from wp_posts p
inner join wp_term_relationships tr on tr.object_id = p.ID
inner join wp_terms t on tr.term_taxonomy_id = t.term_id
inner join wp_term_taxonomy tt on tt.term_taxonomy_id = t.term_id
where post_status ='publish'
and tt.taxonomy = 'category'AND
p.post_date like '2010%'
Where my brain is falling down on the job is figuring out how to then set the post category. What I can see is that the:
- id field in wp_posts is the object_id field in wp_term_relationships
- the object_id field in wp_term_relationships gives us the term_taxonomy_id field
- and the term_taxonomy_id is the term_id in 'wp_terms'
- 'wp_terms' is where the actual category names are stored.
wp_terms table is pretty simple:
[term_id] [name] [slug] [term_group]
[3] [2010] [2010] [0]
How should I go about doing this? It seems that if I know the term_id for 2010 posts should be '3', and if I knew which object_id are 2010 posts, then what I'd do is go into the wp_term_relationships table, and for those object_id's set term_taxonomy_id = '3'.
Right? If so... any hints on writing the SQL for that? (am I overthinking this?)
I could mouse through hundreds of posts and set it by hand, but that seems like the dumb way to do it.
Assumptions & Notes:
{term_id}with the appropriate term_id for each year.Uncategorized.{term_id}with the respective year and term_id.If possible, please test on a sample set of data or staging environment before executing on live data.