WordPress: Insert a post via code

To insert a post programatically, you'll need to make a simple call to wp_insert_post().

$data = array(
'post_status' => 'draft',
'post_type' => 'post',
'post_author' => $user_ID,
'ping_status' => get_option('default_ping_status'),
'post_parent' => 0,
'menu_order' => 0,
'to_ping' => '',
'pinged' => '',
'post_password' => '',
'guid' => '',
'post_content_filtered' => '',
'post_excerpt' => '',
'import_id' => 0,
'post_content' => '',
'post_category' => array(),
'post_title' => ''
);

$post_id = wp_insert_post($data);

add_post_meta($post_id, 'some-field-name', 'this was added programmatically');

Anything in that $data array can be removed because those are the default values.

The trickiest bit is to get the categories working. The post_category bit requires the category ID, which you can get using get_cat_ID('Category Name').

add_post_meta() is optional, in case you needed to append some meta fields to your post.

And thats all there is to it!

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog