Post Pic

WordPress tip: Insert posts programmatically

Do you know that it is possible to insert post in WordPress programmatically? In this recipe, I’ll show you how to do it easily.

Just paste the following code anywhere on WordPress theme files. If you want to test, I recommend pasting it in your functions.php file.
That's all you have to do. Once executed, this code will insert a new post into WordPress database.

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);

Thanks to Matt Harzewski for this great piece of code!

16 Responses

Feb 10 2010 10:56

That right there is the “secret” to the WPVote article submission :)

I was intending to do some sort of write up on it eventually. It’s an incredibly handy feature.

Feb 10 2010 16:46

Rocking Recipe today Jean!

Feb 10 2010 19:12

Great recipe – I wonder if there’s a way to do this with a page, too!

Feb 10 2010 21:59

@Kerrick Long : yes, simply replace ‘post_type’ => ‘post’ by ‘post_type’ => ‘page’ :)

Feb 11 2010 08:56

Nice and useful piece of code.

Thank you !

Feb 12 2010 13:23

good information – thx

Feb 20 2010 18:15

Hi

Good tips !!! Is there a solution to “update” an existing post ?… I search about a solution to add a hook in my functions.php, to update categories checking, from some custom fields values of posts…

:-)

Feb 27 2010 22:25

This is a great tip that I will find very useful! Glad it’s so simple.

Mar 03 2010 02:37

Nice Tricks…

Mar 03 2010 18:07

outstanding!! :D exactly what I needed thanks a lot

Mar 12 2010 15:46

I’ve been looking for something like this for some time now, thanks and the code looks so simple.

Is it possible to do this and also insert values for the All in one SEO pack meta tags at the same time?

Apr 25 2010 17:52

Usefull!

How to insert comments programmatically?

I have been looking the answer for a long time.

Thanks!

May 15 2010 18:21

Could this be used to pull RSS feed items as posts the moment they come out? If so, how? :)

May 26 2010 15:21

Hi there,

First of all thanks for this post. I managed to script a auto post using this snippet. But when i insert the post content breaks after ‘ (apostrophe) . If I echo the content every thing comes up OK. Checked the encoding seems to be OK. any one got any idea..?

Thanks.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required