Wednesday, July 30, 2014

Contact Form 7 - New way to save data from fields

Recently, Contact Form 7 author has updated the plugin to version 3.9 and it seems that a lot has been changed in the back end code and developers are advise to use new methods to access cf7 data.

As per author's update notes,

 if you are a developer of add-on plugins for Contact Form 7 or you have customized Contact Form 7 from your theme’s functions.php file, you may need to modify your code to make it workable with Contact Form 7 3.9.
Here what I do to save new posts / custom post types using the new methods:

New way of saving data before it gets sent as email.


Before, we use the $objval function parameter to get CF7 id and post data
/**
 * CAPTURE CF7, DO SAVE POST
 **/
add_action('wpcf7_before_send_mail', 'do_post_submit_pre_mail_php');
function do_post_submit_pre_mail_php($objval) {
 save_post($objval->posted_data, $objval->posted_data['_wpcf7']);  
 return;
}
Now this is the important part, we should now change this to:
/**
 * CAPTURE CF7, DO SAVE POST
 **/
add_action('wpcf7_before_send_mail', 'do_post_submit_pre_mail_php');
function do_post_submit_pre_mail_php($objval) {
 $submission = WPCF7_Submission::get_instance();
 if ( $submission ) {
    $posted_data = $submission->get_posted_data();
  $cf7id = $objval->id();
 }
 save_post($posted_data, $cf7id);  
 return;
}
Create the save_post function and use the cf7 id to make conditional statements, and the posted data to use as content data.
/**
 * CAPTURE SAVE POST OF CF7, GET THE VALUES AND SAVE IT AS NEW POST
 * content type may depend on form submitted.
 **/
function save_post($values, $cf7id){
 //build array for wp_insert_post
 switch($cf7id){ 
  default:
   $post_title = '';
   $post_type = '';
   $post_content = '';
   $post_status = '';
   $post_author = 1;// 1 = admin
   $customfields = array(
                           'customfieldname' => $values['contact_form_field_name'];
   );
   break;
 }
 $vals = array(
  'post_title' => $post_title,
  'post_status' => 'publish',
  'post_content' => $post_content,
  'post_author' => 1,
  'post_type' => $post_type
 );

 //you can make the below conditional eg. enclose with if($cf7id == 'THEID'){}
 $postid = wp_insert_post($vals);

 if($postid != ""){
  if(is_array($customfields)){
   foreach($customfields as $fkey => $fval){
    updatepostmeta($postid, $fkey, $fval);
   }
  }
 }
}

No comments:

Post a Comment