Programmatically Creating Posts in WordPress
February 9th, 2010 by MattWordPress has a convenient function that can create a new post: wp_insert_post(). Suppose that you wanted to create a plugin to automatically create weekly roundups of your social media activity. You could gather your Delicious bookmarks, Twitter posts, etc. with SimpleXML, mash the data up into a coherent post, then publish the post.
The function syntax is along these lines:
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);
One thing I find particularly interesting is the post_type argument. You could change it to “page” to create a page instead, or you could combine wp_insert_post() with the (as of yet ill-documented) custom post type API to create new admin panels for your post types.
You can edit a post by passing a post ID in the appropriate argument, select multiple categories in the array, or do pretty much anything you can do from the Write screen. After creating the initial post, you can even use the ID that is returned to add custom fields. The full list of parameters for wp_insert_post() is available in the Codex.
It’s a great post, very useful.. I’m not into coding so my question is: it is possible to have also an image for the preview in the code?
What do you mean by that? Do you mean having the post excerpt contain an image, a thumbnail assigned to the post, etc.?
hei, we had similar custom need.
thank you. i have suggestion to give some information to your audience about how to validate their post_content before put into database…to help avoid sql injection
by the way, i have done this and make me try to make pages. i try to make pages but have problem when try to create the pages with its respective template page
Is there a way to add keywords to the post with this method?
Sorry I put keywords, I meant tags.
Thanks
Yes, if you take a look at the Codex page, you’ll see there’s a parameter called “tags_input” that you can pass a comma-delimited string to.