WordPress: How to insert data programmatically

by Jean. 38 Comments -

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' => '127.0.0.1',
	'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.3) 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/

Comments (38) - Leave yours

  1. Daniel Balour said:

    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.

    Thoughts?

  2. Mich said:

    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 said:

      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.

  3. Rolo Tomassi said:

    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..?

  4. Matthew said:

    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!

  5. Niraj said:

    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
    Heading-DEMO

    Name-demo
    Place-demo
    Location-demo
    etc
    den post should continue

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

  6. ian said:

    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.

    • Senad said:

      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.

  7. Carl said:

    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.

  8. downloadtaky said:

    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?

  9. Matt said:

    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!

  10. pog21 said:

    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?

  11. josh said:

    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 ?

  12. pog21 said:

    Thanks. I actually managed to solve the problem using the method described here:
    http://wordpress.stackexchange.com/questions/19732/prevent-duplicate-posts-in-wp-insert-post-using-custom-fields

  13. Mark said:

    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.

  14. Ivo said:

    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.

  15. Richard Mišenčík said:

    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’};

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!