wp_insert_post custom post type

I’m inserting custom post type with following code:

if(isset($_POST['submit'])){

    $post_id = wp_insert_post( array(
                    'post_status' => 'publish',
                    'post_type' => 'custom_type',
                    'post_title' => 'Some post',
                    'post_content' => 'Lorem ipsum'
                ) );

}

and I’m getting error page with; Title: “WordPress failure notice” and text in page “Are you sure you want to do this?

Read More

Please try again.”

But when I try to insert post_type: post then is everything ok.
And everything is ok when i try to insert without isset;

$post_id = wp_insert_post( array(
                        'post_status' => 'publish',
                        'post_type' => 'custom_type',
                        'post_title' => 'Some post',
                        'post_content' => 'Lorem ipsum'
                    ) );

Anybody had same problem?

Related posts

Leave a Reply

4 comments

  1. I have not found solution except this (AND IT WORKS):

    if(isset($_POST['submit'])){
    
        $post_id = wp_insert_post( array(
                        'post_status' => 'publish',
                        'post_type' => 'post',
                        'post_title' => 'Some post',
                        'post_content' => 'Lorem ipsum'
                    ) );
    
    $post_type = 'custom_type';
    
    $query = "UPDATE {$wpdb->prefix}posts SET post_type='".$post_type."' WHERE id='".$post_id."' LIMIT 1";
    
    GLOBAL $wpdb; 
    
    $wpdb->query($query);
    
    }
    
  2. I got mine to work with this:

    PHP, placed before the header:

    if(isset($_POST['new_post']) == '1') {
    
    $new_post = array(
          'ID' => '',
          'post_type' => 'customtype', // Custom Post Type Slug
          'post_status' => 'publish',
          'post_title' => $_POST['post_title'],
        );
    
    $post_id = wp_insert_post($new_post);
    $post = get_post($post_id);
    }
    

    and in the HTML:

    <form method="post" action="">
    
          <input name="post_title" type="text" />
    
          <input type="hidden" name="new_post" value="1" />
          <input type="submit" name="submit" value="Post" />
    
    </form>
    
  3. Try this out this is the form header

    <form id="insert_new_lesson" name="insert_new_lesson" method="post" action="" class="lesson-form">;
    

    The if statement I make is this

    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && 'insert_new_lesson' == $_POST['action'] )