using $wpdb to insert a form into a post

I am wanting to take the following form, and use $wpdb to insert it into a post. I have tried reading the class reference page INSERT rows, but I don’t really know what should be referenced. I am not sure how to tell the form to insert the data into a post using $wpdb?

<?php
if (isset($_POST['pickup-form']))
{
    // Clean POST data
    $demo_input = (isset($_POST['demo-input'])) ? trim((string) $_POST['demo-input']) : '';

    // Validate POST data
    if ('' === $demo_input)
    {
        $errors['demo_input'] = __('Demo field is required');
    }

    // No errors
    if (empty($errors))
    {
        // Save POST data to database, send some e-mails, etc.
        $success = TRUE;
    }
}
?>

<?php if ( ! empty($success)) { ?>

    <p>Thank you!</p>

<?php } else { ?>

    <?php if ( ! empty($errors)) { ?>
        <?php print_r($errors) ?>
    <?php } ?>

    <form method="post" action="">
        <input type="hidden" name="pickup-form">
        <input type="text" name="demo-input" value="<?php if (isset($demo_input)) { echo esc_attr($demo_input); } ?>">
        <input type="submit">
    </form>

<?php } ?>

Related posts

Leave a Reply

1 comment

  1. In the success part of your code, you can build an array representing a post, and use wp_insert_post as such :

    Example

     $mypost = array(
          'post_title' => 'My Title',
          'post_type' => 'page'
          //... add other fields according to your form
     );
    
     $mypost_id = wp_insert_post( $mypost ); //Returns new post id on success
    

    Any field you don’t specify will be filled by WordPress automatically.

    EDIT

    For custom fields, see add_post_meta :

     $mypost_id = wp_insert_post( $mypost ); //SEE ABOVE
     $meta_key = 'your-new-field-name';
     $meta_value = 'your-form-value';
     $unique = true; // or false     
    
     add_post_meta( $mypost_id, $meta_key, $value, $unique );
    

    Source : wp_insert_post