I'm working in WordPress with Contact Form 7. I'm dynamically creating a Word Document based on the users submitted data, and I want to attach that file to the e-mail that the user is sent from Contact Form 7.
To confirm, the file is created and saved in the correct location. My issue is definitely with attaching it to the e-mail from CF7.
I have the following code at the moment:
add_action('wpcf7_before_send_mail', 'cv_word_doc');
function cv_word_doc($WPCF7_ContactForm) {
// Check we're on the CV Writer (212)
if ( $WPCF7_ContactForm->id() === 212 ) {
//Get current form
$wpcf7 = WPCF7_ContactForm::get_current();
// get current SUBMISSION instance
$submission = WPCF7_Submission::get_instance();
if ($submission) {
// get submission data
$data = $submission->get_posted_data();
// nothing's here... do nothing...
if (empty($data))
return;
// collect info to add to word doc, removed for brevity...
// setup upload directory and name the file
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['basedir'] . '/cv/';
$fileName = 'cv-' . str_replace(' ', '-', strtolower($firstName)) . '-' . str_replace(' ', '-', strtolower($lastName)) .'-'. time() .'.docx';
// PHPWord stuff, removed for brevity...
// save the doc
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($upload_dir . $fileName);
// add upload to e-mail
$submission->add_uploaded_file('docx', $upload_dir . $fileName);
// carry on with cf7
return $wpcf7;
}
}
}
Everything works up until $submission->add_uploaded_file('docx', $upload_dir . $fileName);
.
There's not much documentation about, but I have read that I need to include something similar to:
add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );
function mycustom_wpcf7_mail_components( $components ) {
$components['attachments'][] = 'full path of your PDF file';
return $components;
}
In order to get the attachment to show. However, I don't know how I can get the specific file that I need, as the file is unique to each submission and all of the variables will be in a separate function.
Fixed this issue.
I added:
// make file variable global
global $CV_file;
$CV_file = $upload_dir . $fileName;
after $submission->add_uploaded_file('docx', $upload_dir . $fileName);
Then seperate to the add_action
, I used the filter and referenced the global var:
add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );
function mycustom_wpcf7_mail_components( $components ) {
global $CV_file;
$components['attachments'][] = $CV_file;
return $components;
}