WordPress: How to insert data programmatically

Recently, a client of mine asked me to write an article importer for his WordPress powered site, which was a very interesting project for me. In this article, I'll show you how you can easily add data (posts, comments, categories, etc) to your WordPress blog, without any manual effort.

Inserting posts

Do you remember back in 2008, when I created WP Vote? This site was the first (as far as I know) social voting site created 100% within WordPress. Users were able to submit a story, which was automatically published on the blog.

Inserting a post programmatically in WordPress is extremely easy. You have to use the wp_insert_post() function, which takes an array as a parameter.
Here is a working example. If you want to test it, paste the code below on your functions.php file.

global $user_ID;
$new_post = array(
    'post_title' => 'My New Post',
    'post_content' => 'Lorem ipsum dolor sit amet...',
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => $user_ID,
    'post_type' => 'post',
    'post_category' => array(0)
$post_id = wp_insert_post($new_post);

Cool, isn’t it? Let have a closer look to the parameters specified in the $new_post array:

  • post_title: the name of the post.
  • post_content: the content of the post
  • post_status: the post status (published, draft, etc)
  • post_date: use date() or specify a custom date
  • post_author: Author id of the post author
  • post_type: Can be post, page, or a custom post type
  • post_category An array of categories ids

Source: http://www.webmaster-source.com/2010/02/09/programmatically-creating-posts-in-wordpress

Inserting comments

Inserting comments is not harder than inserting posts. I personally never used this code, but here is it in case you need it. To give it a try, simply paste it in your functions.php file.

$data = array(
	'comment_post_ID' => 1,
	'comment_author' => 'admin',
	'comment_author_email' => 'admin@admin.com',
	'comment_author_url' => 'http://www.catswhocode.com',
	'comment_content' => 'Lorem ipsum dolor sit amet...',
	'comment_author_IP' => '',
	'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv: Gecko/20100401 Firefox/3.6.3',
	'comment_date' => date('Y-m-d H:i:s'),
	'comment_date_gmt' => date('Y-m-d H:i:s'),
	'comment_approved' => 1,

$comment_id = wp_insert_comment($data);

Just like the wp_insert_post() function, wp_insert_comment() takes an array as a parameter. Here are the data used:

  • comment_post_ID: ID of the commented post
  • comment_author: Name of the comment author
  • comment_author_email: Email address of the comment author
  • comment_author_url: Website of the comment author
  • comment_content: Text of the comment
  • comment_author_IP: IP address of the comment author
  • comment_agent: User agent of the commenter browser
  • comment_date: Date of the comment
  • comment_date_gmt: GMT date of the comment
  • comment_approved: Is the comment approved? 1 for yes and 0 for “awaiting moderation”

Adding categories to a post

Now that we saw how to insert a post or a comment into WordPress database, let’s see how to make a post part of one (or more) categories. WordPress has a built-in function for that, named wp_set_object_terms().

What you have to do is to create an array with the desired categories ID, and then use the function as shown below:

$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');

The wp_set_object_terms() function take 3 parameters: The post ID, an array of categories ID, and the taxonomy type (In this example, category).

Adding tags to a post

Adding tags to a post is extremely simple as well. Even better, it does not require a new function, you can do so by using wp_set_object_terms().
Take a look at the example below:

$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');

Looks very similar with the previous piece of code, which allowed us to add categories to a post, isn’t it? In fact, the only difference is the taxonomy type: Here the parameter is post_tag instead of category.
Source: http://wpprogrammer.com/snippets/add-a-category-or-tag-to-a-post-programatically/

Automatically create a custom field when a post is published

I recently had a client who wanted to have a custom field created automatically, each time he published a new post, so he wouldn’t have to create a custom field with a default value for each article he wrote.
This piece of code was a real life-saver: Just paste it on your functions.php file and publish a new post: A custom field has been created automatically.

function add_custom_field_automatically($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
		add_post_meta($post_ID, 'field-name', 'custom value', true);
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');

So how does it work? First, a function has been created. This function make sure the post isn’t a revision on then adds a custom field named field-name, with custom value as a value.
Then, a “hook” is used to make sure that every time a post or page will be published, the add_custom_field_automatically() function will be called.
Source: http://wpcanyon.com/tipsandtricks/adding-a-custom-field-automatically-on-postpage-publish/

  • I know plenty of people who would just about kill for this info. Awesome article! Even if it did end a bit abruptly… 🙂

  • Daniel Balour

    Awesome post JB.

    As per my tweet, I’d love it if you could elaborate with an example or two on *specifically* how to make this work with custom post types. I know it’s supposed to be the same thing, for the most part only varying the post-type argument. However, I’ve run into a situation where “content” was not an enabled field in my custom type and for some reason I couldn’t populate my database programmatically.


    • It can work with custom post types with no extra configuration: Just change this line:
      ‘post_type’ => ‘post’,


      ‘post_type’ => ‘your-custom-post-type’,


  • Thanks for including my tip Jean.

  • Could you give an example of how and why you would use these functions. Maybe, I’m missing something…

    • open your themename/functions.php or create a functions.php file
      copy & paste the code above
      reload your frontend page

      that´s it

    • About the why part, maybe some kind of blog where people can tag your articles would be a fun idea 🙂

    • If you ever wanted to let people submit pending articles via a form on your blog, this is a great solution.

  • I think it will be much easier to create an XML file and import what is necessary. For new blog, SQL dump will do the job, however there are many options for WordPress, as the CMS is very flexible.

    • Daniel Balour

      Not if you need to *generate* blog posts based on a specific criteria. Say you wanted to create a dummy data file with different post-types in order to prototype a theme, you’d have to manually create each and every entry of your XML file. With this method, you could write a bit of php code, setup some paramaters, incrementing vars and presto, you’ve got a dataset.

  • I’m not sure if this is particularly relevant however there are quite a few .csv plugins for WordPress that allow you to mass submit data… although maybe I’ve confused the purpose of progamatically entered data..?

  • Great post, I just did this with the user news section of our site.

  • Interesting. You could create your own “submit form” with a “pending” list or something and then publish the post.


  • good woork thanks

  • Just curious about this, could one do this with data already in the the database and apply it to a custom taxonmy added to an attachment?

  • This really is some great info – have you thought about compiling an ebook on this? I know people who would buy it – you could make a fortune!

  • Niraj

    Hey i hav a question
    is it possible to add a text box and a label in dashboard – in add new post
    so dat the editor gets an easy option to enter the data in proper order and it should be displayed b4 the post after the heading
    for eg in dashboard it should appear in such a way

    den post should continue

    is dis possible?
    nd yes den how
    plzzz help me its urgent

  • ian

    I’m just starting and still learning about wordpress, this will be a great help to me soon as i get in to more of the “technical” sort of thing in word press. thanks for sharing.

  • Awesome Article. I have used this trick once to recover all the categories which I converted it into tags .

    Thanks for the information

  • I manage six blogs. This info helps! Thank you!

  • thanks for sharing but i can’t understand what the use of that why i enter that info pragmatically ??

    • Say you bought a database of 10 000 posts. You could make a nice little script that every day ads 10 new posts for you. So without doing anything, the site is getting updated. I take that as an example because that is what my case is. Great article.

  • Genius! Thanks for sharing this info/tip. It makes editing easier especially if you are managing a lot of blog sites.

  • Do you also know how we can automatically set image sizes in the Media Settings through coding? It can be useful for theme building…

  • … and maybe make it un-editable to users (so they are fixed values)…

  • Great post, I just did this with the user news section of our site.

  • A couple of weeks ago I did something similar, there were tons of articles that I had to publish to a blog. My method was very similar, but more basic.

  • Hi, I’ve used your “automatic” comment submitter to test the template I’m creating but I would like to use it “normally” I try to explain what I wanna say. Your code adds(?) a comment each time I reload the page and this is not good if I would like to use it on my “real” website… Do you know how to fix if? How to run it only once for each post?

  • Post is very curious, I could one do this with data already in the the database and apply it to a custom taxonmy added to an attachment and do the rest process?

  • I’ve dabled a little in trying to customize my WP themes but it always takes me longer than id like. Anyway, just the stuff I was looking for. Thanks for sharing!

  • Thanks for sharing this JP! I needed this code today 🙂 cheers!

  • pog21

    Thanks for the post – very useful! However… I’ve found that the posts are being created 3 times (each). Printing to screen just before calling wp_insert_post shows only single, so I’m pretty stumped! Any ideas?

  • your earlier error was because of wrong code for insert.

    This error is because of connection problem.(First you solve this)
    Are you able to access other database related page with same connection string ?

  • Thanks. I actually managed to solve the problem using the method described here:

  • Mark

    How does this work? Where do I need to call the wp_insert_post() function?

    Or in other words, if I have the text “This is a new post”, what do I need to put into a new php file to post this text automatically to my blog?

    Any help is very much appriated.

  • Jai

    Great info and I understand it but am at a loss as to where to put it. What includes do I need to add.

  • Ivo

    I also don’t understand what I should include in order for wp_insert_post to work. I don’t want to put the code in functions.php file, I want it in my php project.

  • Richard Mišenčík

    How about setting different post_content for each post?
    Could it be possible with a php file which contains the logic?
    Something like this:
    ‘post_content’ => ‘posts-content.php’

    And inside that you would do, if(‘post_title’ == ‘Home’) { echo ‘Default home page content’};