Need to insert custom post type objects from code. Haven't been able to add using the default method

$id = wp_insert_post(array('post_title'=>'random', 'post_type'=>'custom_post'));

creates a regular post instead.

  • Have you registered a custom post type named as custom_post before using this call? – Rohit Pande Jul 18 '13 at 11:32
  • yes its registered – rashid Jul 18 '13 at 11:56
  • never mind, its working, there was a minor bug in the file, this exact snippet is correct. just replace 'custom_post' with post type of your choosing! – rashid Jul 18 '13 at 12:02

From the Codex:

wp_insert_post() will fill out a default list of these but the user is required to provide the title and content otherwise the database write will fail.

$id = wp_insert_post(array(
  'post_content'=>'demo text'
| improve this answer | |

It can be done using the following code :-

To enter a new post for a custom type

$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',   // if you prefer
   'ping_status' => 'closed',      // if you prefer

After inserting the post, a post id will be returned by the above function. Now if you want to enter any post meta information w.r.t this post then following code snippet can be used.

if ($post_id) {
   // insert post meta
   add_post_meta($post_id, '_your_custom_1', $custom1);
   add_post_meta($post_id, '_your_custom_2', $custom2);
   add_post_meta($post_id, '_your_custom_3', $custom3);
| improve this answer | |
  • The 'meta_input' parameter can be used in the 'wp_insert_post' array, to add meta fields, instead of using 'add_post_meta' afterward. – AncientRo Mar 10 '19 at 14:14
  • Thanks for the post. @AncientRow, can you provide an example including meta_input? – Pegues Apr 22 at 17:39

I found using isset() allowed me to use wp_insert_post() on custom post types:

if ( !isset( $id ) ) { 
    $id = wp_insert_post( $new, true ); 
| improve this answer | |
  • To properly format code in your answer (or question), highlight it and click {} above the edit box. – Gabriel Mar 10 '15 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.