WordPress: Insert a post via code

0 Comments

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

01.$data = array(
02.  'post_status' => 'draft',
03.  'post_type' => 'post',
04.  'post_author' => $user_ID,
05.  'ping_status' => get_option('default_ping_status'),
06.  'post_parent' => 0,
07.  'menu_order' => 0,
08.  'to_ping' => '',
09.  'pinged' => '',
10.  'post_password' => '',
11.  'guid' => '',
12.  'post_content_filtered' => '',
13.  'post_excerpt' => '',
14.  'import_id' => 0,
15.  'post_content' => '',
16.  'post_category' => array(),
17.  'post_title' => ''
18.);
19. 
20.$post_id = wp_insert_post($data);
21. 
22.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