Skip to content

Instantly share code, notes, and snippets.

@hachesilva
Created March 30, 2015 22:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hachesilva/82089ee3bd3c1ad177d9 to your computer and use it in GitHub Desktop.
Save hachesilva/82089ee3bd3c1ad177d9 to your computer and use it in GitHub Desktop.
Create a Wordpress post after a Contact Form 7 form submission, for contact form 7 v.3.9 or newer
<?php
// Add this to your functions.php file
add_action( 'wpcf7_before_send_mail', 'mytheme_save_post');
function mytheme_save_post( $cf7 ) {
try {
if (!isset($cf7->posted_data) && class_exists('WPCF7_Submission')) {
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$data = array();
$data['title'] = $cf7->title();
$data['posted_data'] = $submission->get_posted_data();
$data['uploaded_files'] = $submission->uploaded_files();
$post = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_status' => 'publish',
'post_type' => 'post',
'post_title' => $data['posted_data']['your-title'],
'post_name' => sanitize_title($data['posted_data']['your-title']),
'post_content' => $data['posted_data']['your-content']
);
$postId = wp_insert_post($post);
return $postId;
}
}
} catch (Exception $ex) {
print $ex;
}
return true;
}
@selectiveform
Copy link

How do you assign that cf7 to a specific custom post type?

@ksider
Copy link

ksider commented Sep 17, 2015

'post_type' => 'custom-post-type',

@jarc100
Copy link

jarc100 commented Jan 20, 2016

How do i set which Form should insert the post?

Edit:

Ok, i know how. If anyone else happens to be as newbie as me:
You change ['title'] by your form's title name.

$data['myCF7nameTitle'] = $cf7->title();

@viniciusf84
Copy link

Thank you so much for sharing this code.

How can I upload a featured image?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment