
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.

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
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.
Rocking Recipe today Jean!
Great recipe – I wonder if there’s a way to do this with a page, too!
@Kerrick Long : yes, simply replace ‘post_type’ => ‘post’ by ‘post_type’ => ‘page’
Nice and useful piece of code.
Thank you !
good information – thx
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…
This is a great tip that I will find very useful! Glad it’s so simple.
Nice Tricks…
outstanding!!
exactly what I needed thanks a lot
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?
Usefull!
How to insert comments programmatically?
I have been looking the answer for a long time.
Thanks!
Could this be used to pull RSS feed items as posts the moment they come out? If so, how?
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: