22

I have a custom post type 'Participant' with many custom fields. I also have a form with corresponding input fields for the user to fill out. When he submits the form, I want a new post to be generated with each custom fields containing the value chosen by the user.

Is it possible to do and if so, how?

3 Answers 3

44

Use wp_insert_post() and add_post_meta(), like this:

// insert the post and set the category
$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
));

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);
}
5
  • Works as charm even on WordPress 4.4.2 :) !
    – jave.web
    Apr 11, 2016 at 6:12
  • nowadays, you can simply add meta fileds via the meta_input key in wp_insert_post: 'meta_input' => ['_your_custom_1' => $custom1, '_your_custom_2' => custom2]
    – Andreas
    May 21, 2019 at 11:08
  • Good point @Andreas, I suggest that you add that as a new answer and let it start getting up votes. It should be the answer now.
    – webaware
    May 21, 2019 at 22:48
  • Thx @webaware :)
    – Andreas
    May 22, 2019 at 23:58
  • Works as charm even on WordPress 5.1 :) ! Jun 6, 2019 at 4:43
14

In addition to the great answer of @webaware above, this can be handled since wordpress 4.4.0 all via the wp_insert_post call:

$post_id = wp_insert_post(array (
    'post_content' => $content,
    'post_title' => $title,
    'post_type' => 'your_custom_post_type',
    'post_status' => 'publish',

    // some simple key / value array
    'meta_input' => array(
        'your_custom_key1' => 'your_custom_value1',
        'your_custom_key2' => 'your_custom_value2'
        // and so on ;)
    )
));

if ($post_id) {
    // it worked :)
}

4

This can be achieved quite easily using the Gravity Forms plugin. You can build a form which populates a Custom Post Type in the backend. This post can be set to appear as a draft or as published. No problem adding custom fields. In my case, I used it to gather client testimonials.

1
  • I like this solution, especially if you're delivering it to a client that wants to manage the form themselves.
    – webaware
    Dec 26, 2012 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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