Support » Fixing WordPress » Add category via SQL

  • Through a combination of circumstances – changing the IA/category structure of my blog, a move to mostly using tags, imports, exports, upgrades, etc. I have a situation where a large number of my posts have no category.

    They’re not assigned the default “Uncategorised”; it doesn’t even exist for the purposes of my blog. They actually have no category.

    What I want is a quick SQL script that will assign a known category to these posts. I just need some help with the SQL to assign it.

    Can anyone offer some ideas, please?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42) Admin

    If there is already the category (term), then you need to do this.

    First, find the term in the terms table. Get its term_id.

    Next, look in the term_taxonomy table to find its term_taxonomy_id. This will be the entry matching the term_id you found already and having a taxonomy of ‘category’.

    Next, get the ID value from the posts table of all the posts you want to assign to that category.

    Then do this for each of them:
    INSERT INTO term_relationships (object_id, term_taxonomy_id) VALUES (POST_ID, TERM_TAXONOMY_ID);

    Obviously replace POST_ID and TERM_TAXONOMY_ID with the post id’s and the term_taxonomy_id numbers.

    The SQL query above worked great for adding categories to posts in bulk. However, the category count didn’t seem to update on its own. So there’s probably some additional SQL action needed to make it all sync up. Anyone have any pointers?


    Aha… looks like this post has the solution:

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add category via SQL’ is closed to new replies.