7

I have content from elsewhere that I would like to insert as a post in Wordpress and then associate with an existing category. It is pretty straightforward to insert a new post into the wp_posts table, but I can't seem to figure out how to construct a query to both insert a new post and at the same time associate the post with a category. How would one go about doing this?

If it helps, I am using WordPress 2.8

2
  • Do you want to do it with SQL or are WordPress functions acceptable too? Jul 23, 2009 at 15:27
  • Edit: Actually, I would prefer SQL so that I can run a script outside of wordpress. Submitted my comment a little too quickly. Jul 23, 2009 at 15:41

3 Answers 3

16

Use this query:

INSERT INTO wp_posts (post_title,post_content,post_name,post_date,post_date_gmt,post_modified,post_modified_gmt,post_author,post_status) 
VALUES ('title','text','post_name',now(),now(),now(),now(),1,'publish')

INSERT INTO wp_term_relationships (object_id,term_taxonomy_id) VALUES ([the_id_of_above_post],1)
1
  • Thanks for spelling things out. Jul 27, 2009 at 13:49
5

Categories are stored in the wp_terms tables, with a cross-reference between wp_posts and wp_terms stored in the wp_term_relationships table.

So, you would first need to insert your post into the wp_posts table, and then for each of the existing categories that you want to associate it with, insert a record into the wp_term_relationships table.

More info here: WordPress Database Description

5

use the wp_insert_post function then use the wp_set_post_categories function

http://codex.wordpress.org/Function_Reference for usage information

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.