Home > Back-end >  Create WordPress Posts from Contact form 7 submissions
Create WordPress Posts from Contact form 7 submissions

Time:11-17

Quick warning, I'm not good at php coding, keep it as simple as possible :).

I am looking for a solution where guests can write in a Contact form 7 form and when they submit it, a WordPress post is automatically created based on their entered information.

I created this code, but I can't figure out the problem since no posts are created.

function save_cf7_data_to_cpt($contact_form)
{

    if ($contact_form->id(11247) !== $my_form_id) return;
    $submission = WPCF7_Submission::get_instance();
    if ($submission)
    {
        $posted_data = $submission->get_posted_data();
    }
    $args = array(
        'post_type' => 'post',
        'post_status' => 'draft',
        'post_category' => array(91),
        'post_title' => $posted_data['text-410'],
        'post_content' => $posted_data['textarea-420'],
        'post_date' => $posted_data['date'],

    );
    $post_id = wp_insert_post($args);
}

add_filter('wpcf7_before_send_mail', 'save_cf7_data_to_cpt');

When I submitted my information, I got the usual confirmation message from Contact Form 7 but no post was made.

CodePudding user response:

$my_form_id is undefined in your function you can use wpcf7_mail_sent hook to get posted data and add that data to your post.

Try Out this code.

add_action( 'wpcf7_mail_sent',
  function( $contact_form) {
      
     $my_form_id = 711; //form id for post data

    if ($contact_form->id() != $my_form_id) return;

      $submission = WPCF7_Submission::get_instance();  
      if ( $submission ) {
          $posted_data = $submission->get_posted_data();
      }   
      
      $args = array(
        'post_type' => 'post',
        'post_status' => 'draft',
        'post_category' => array(91),
        'post_title' => $posted_data['text-410'],
        'post_content' => $posted_data['textarea-420'],
        'post_date' => $posted_data['date'],
    );
    $post_id = wp_insert_post($args);
 
    // Do some productive things here
  },
  10
);
  • Related